0

我正在尝试使用代码中的“topicPostArea.setCellRenderer”方法将存储在 Jlabel 中的数据转换为 JList,原因是我有一些删除功能,需要先将数据存储在列表中删除内容。

如果有人可以建议如何使用我已经到位的代码来完成这将不胜感激。

import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.event.UnknownEventException;
import net.jini.core.lease.Lease;
import net.jini.space.JavaSpace;

import javax.swing.*;
import java.awt.*;
import java.rmi.RemoteException;


public class MRHomePage extends JFrame implements RemoteEventListener {

private static final long TWO_SECONDS = 2 * 1000;  // two thousand milliseconds
private static final long ONESECOND = 1000;  // one thousand milliseconds
private JavaSpace space;
private JTextField newComment, jobNumberOut, topicIn, usernameString;
private Label username;
private JList topicPostArea, topicStoreArea;
private JTextArea box, privateArea;
public LoginPage login;
public JComboBox allTopics;
public String currentUser;
public DefaultListModel<MRQueueTopicCreate> topicListModel;


public MRHomePage() {
    space = SpaceUtils.getSpace();
    if (space == null) {
        System.err.println("Failed to find the javaspace");
        System.exit(1);
    }
    initComponents();
    pack();
    printPosts();
    startUP();
    //addTopic();
    setVisible(true);

}

public static void main(String[] args) {

    new MRHomePage().setVisible(true);
}

public void initComponents() {

    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            System.exit(0);
        }
    });

    //container
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());

    //panels
    JPanel jPanel1 = new JPanel();
    jPanel1.setLayout(new FlowLayout(FlowLayout.LEFT));

    JPanel jPanel2 = new JPanel();
    jPanel2.setLayout(new FlowLayout());

    JPanel jpanel3 = new JPanel();
    jpanel3.setLayout(new FlowLayout());



    //labels
    JLabel commentLabel = new JLabel();
    JLabel topicLabel = new JLabel();
    JLabel userNameLabel = new JLabel();


    //text fields
    usernameString = new JTextField(12);
    topicIn = new JTextField(7);
    newComment = new JTextField(3);
    jobNumberOut = new JTextField(2);

    //text Area
    privateArea = new JTextArea(30,30);

    topicListModel = new DefaultListModel<>();

    topicPostArea = new JList();
    topicStoreArea = new JList();



    topicPostArea.setCellRenderer(new ListCellRenderer<MRQueueTopicCreate>() {
        @Override
        public Component getListCellRendererComponent(JList list, MRQueueTopicCreate value, int index, boolean isSelected, boolean cellHasFocus) {
            JLabel jLabel = new JLabel();
            jLabel.setText( "[" + "User:" + " "  + " - " + "Topic: " +
                    value.Topic + " - " + "Comment: " + value.Comment + "]" + "\n");
            return jLabel;
        }
    });
    topicPostArea.setModel(topicListModel);
    box = new JTextArea(30, 30);



    //buttons
    JButton getButton = new JButton();

    JButton addTopicButton = new JButton();

    JButton deleteTopicButton = new JButton();


    //add areas to panels
    jpanel3.add(box);
    box.setEditable(false);
    jpanel3.add(topicPostArea);
    //topicPostArea.setEditable(false);
    jpanel3.add(privateArea);
    privateArea.setEditable(false);


    //set label text
    topicLabel.setText("Topic ");
    commentLabel.setText("Comment ");
    userNameLabel.setText("Username ");
    getButton.setText(" Get ");
    addTopicButton.setText("Post Topic");
    deleteTopicButton.setText("Delete private content");


    topicIn.setText("");
    newComment.setText("");
    jobNumberOut.setText("");


    jPanel2.add(topicLabel);
    jPanel2.add(topicIn);
    topicIn.setEditable(true);


    jPanel2.add(commentLabel);
    jPanel2.add(newComment);
    newComment.setEditable(true);

    jobNumberOut.setEditable(true);
    jPanel1.add(jobNumberOut);


    jPanel1.add(userNameLabel);

    currentUser = LoginPage.user.getUsername();
    usernameString.setText(LoginPage.user.getUsername());
    usernameString.setEditable(false);
    jPanel1.add(usernameString);







    //action performed


    getButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            getSobj(evt);
        }
    });

    addTopicButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addTopic(evt);
        }
    });


    deleteTopicButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deleteTopic(evt);
        }
    });


    jPanel2.add(addTopicButton);

    jPanel2.add(getButton);

    jPanel2.add(deleteTopicButton);


    cp.add(jPanel1, "North");
    cp.add(jPanel2, "South");
    cp.add(jpanel3, "Center");

}


//methods


public void deleteTopic(java.awt.event.ActionEvent evt) {
    String comment = newComment.getText();
    String topic =  topicIn.getText();

    try {

        MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic);
        space.write(topicLog, null, Long.MAX_VALUE);
        topicLog.setTopic(topic);
        topicLog.setComment(comment);

        space.write(topicLog, null, Lease.FOREVER);

        //jobNumberOut.setText("" + topic);
        // jobNameIn.setText("" + comment);
        MRQueueTopicCreate template = topicListModel.elementAt(topicPostArea.getSelectedIndex());
        //if (template.owner = currentUser.username) {
        topicListModel.remove(topicPostArea.getSelectedIndex());


        space.take(template, null, 1000*2);
        //}

    }catch (Exception e) {
        e.printStackTrace();
    }
}

public void addTopic(java.awt.event.ActionEvent evt) {
    String comment = newComment.getText();
    String topic = topicIn.getText();

        try {

            MRQueueTopicCreate topicLog = new MRQueueTopicCreate(comment, topic);
            space.write(topicLog, null, Long.MAX_VALUE);
            topicLog.setTopic(topic);
            topicLog.setComment(comment);

            space.write(topicLog, null, Lease.FOREVER);

            //jobNumberOut.setText("" + topic);
           // jobNameIn.setText("" + comment);
            topicListModel.addElement(topicLog);

            //box.append("[" + "User:" + " " + LoginPage.user.getUsername() + " - " + "Topic: " + topic + "]" + "\n");

            //topicPostArea.append("[" + "User:" + " " + user + " - " + "Topic: " + topic + " - " + "Comment: " + comment + "]" + "\n");
    }catch (Exception e) {
        e.printStackTrace();
    }
}

public void printPosts() {
    try {
        QueueItem qiTemplate = new QueueItem();
        QueueItem nextJob = (QueueItem) space.take(qiTemplate, null, TWO_SECONDS);
        if (nextJob == null) {
            // no print job was found, so sleep for a couple of seconds and try again
            Thread.sleep(TWO_SECONDS);
        } else {
            // we have a job to process
            int nextJobNumber = nextJob.jobNumber;
            String nextJobName = nextJob.filename;
            String nextTopic = nextJob.topicName;
            box.append("Job Number: " + nextJobNumber + " " + "Topic" + nextTopic + " " + "\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void getSobj(java.awt.event.ActionEvent evt) {
    QueueLogin template = new QueueLogin();
    try {
        QueueLogin got = (QueueLogin) space.take(template, null, TWO_SECONDS);
        if (got == null)
            usernameString.setText("No object found");
        else // use this to diplay all contents into the outstring textfield.
            usernameString.setText(got.username);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void startUP() {
    JavaSpace space = SpaceUtils.getSpace();

    if (space == null) {
        System.err.println("Failed to find the javaspace");
        System.exit(1);
    }

    QueueStatus template = new QueueStatus();
    try {
        QueueStatus returnedObject = (QueueStatus) space.readIfExists(template, null, ONESECOND);
        if (returnedObject == null) {
            // there is no object in the space, so create one
            try {
                QueueStatus qs = new QueueStatus(0);
                space.write(qs, null, Lease.FOREVER);
                System.out.println("QueueStatus object added to space");
                System.exit(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // there is already an object available, so don't create one
            System.out.println("QueueStatus object is already in the space");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void registerForEvents() {

}

@Override
public void notify(RemoteEvent remoteEvent) throws UnknownEventException, RemoteException {
    //look for Gary's code on this
}
}

模型

import net.jini.core.entry.Entry;

public class MRQueueTopicCreate implements Entry {
// Variables
public String Topic;
public String Comment;

// No arg contructor
public MRQueueTopicCreate() {
}

// Arg constructor
public MRQueueTopicCreate(String tp, String cm) {
    this.Topic = tp;
    this.Comment = cm;
}

public String getTopic() {
    return Topic;
}
public String getComment() {
    return Comment;
}

public void setTopic(String topics) {
    this.Topic = topics;
}
public void setComment(String comments) {
    this.Comment = comments;
}

}
4

1 回答 1

0

Swing 组件默认显示每个数据对象的字符串形式。因此,您可以删除单元格渲染器,并在您的 MRQueueTopicCreate 类中提供一个 toString 方法:

public class MRQueueTopicCreate implements Entry {
    // ...

    @Override
    public String toString() {
        return "[" + "User:" + " " + " - " + "Topic: " +
            Topic + " - " + "Comment: " + Comment + "]";
    }

作为奖励,您的 JList 将是可访问的——这意味着,它将与视障用户使用的屏幕阅读器一起使用,而您无需付出额外的努力。另一方面,自定义渲染器不能被辅助技术解释。

没有理由放在\n文本的末尾。JList 已经在视觉上分离了项目。

将来,如果您出于任何其他原因碰巧实现了单元格渲染器,则应该扩展 DefaultListCellRenderer。您的自定义渲染器每次都会创建一个新的 JLabel,这很昂贵(因为当用户与渲染器交互时会非常频繁地调用渲染器),甚至可能会影响性能。

于 2018-12-11T19:28:20.743 回答