尝试使用setCellRenderer将JLabel转换为JList



我正试图使用代码中的"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;
}
}

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

public class MRQueueTopicCreate implements Entry {
// ...
@Override
public String toString() {
return "[" + "User:" + " " + " - " + "Topic: " +
Topic + " - " + "Comment: " + Comment + "]";
}

作为奖励,您的JList将可访问,这意味着它将与视力受损用户使用的屏幕阅读器一起工作,而无需您付出额外的努力。另一方面,自定义渲染器无法通过辅助技术进行解释。

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

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

最新更新