我知道这个问题以前问过很多次。但是,我花了几个小时研究更新 JList 的方法,但我无法处理这个问题。我正在尝试实现一个 JList 来显示谁在线或离线。(它包含 JLabels 我想这是保存带有图标的字符串的唯一方法)。我有我自己的CellRenderer()
,就像;
public class UserRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean hasFocus) {
if(value instanceof ClientObject){
final ClientObject clientObject = (ClientObject) value;
JLabel label = (JLabel) super.getListCellRendererComponent(list, clientObject.getNickName(), index, isSelected, hasFocus);
if(clientObject.isIsOnline()){
label.setIcon(iconArray[1]);
}
else{
label.setIcon(iconArray[0]);
}
return label;
}
else {
return super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
}
}
}
此外,每当他/她以这种方式连接到服务器时,我都会构建客户的列表;
private void buildBuddyList(ClientObject tempClientObject){
if( tempClientObject.getBuddyList().size() > 0 ){
mainClient.setBuddyList(tempClientObject.getBuddyList());
for (Iterator<ClientObject> iter = mainClient.getBuddyList().iterator(); iter.hasNext();) {
ClientObject tempon = iter.next();
if(tempon.isIsOnline()){
model.addElement(tempon);
labelIconList.put(tempon, iconArray[1]);
}
else{
model.addElement(tempon);
labelIconList.put(tempon, iconArray[0]);
}
}
}
}
当客户改变他/她的状态(变为在线/离线)时,我使用的技巧是我摆脱所有元素model.clear()
并重新开始构建列表。这是代码段;
if(tempClientObject.isStatusChanged()){
if(tempClientObject.isIsConnected()){
System.out.println(tempClientObject.getUserName() + " is ONLINE");
model.clear();
for (Iterator<Map.Entry<ClientObject,ImageIcon>> iter = labelIconList.entrySet().iterator(); iter.hasNext();) {
Map.Entry<ClientObject,ImageIcon> pairs = iter.next();
ClientObject changedOnlineStatusClient = (ClientObject) pairs.getKey();
if(changedOnlineStatusClient.getUserName().equals(tempClientObject.getUserName())){
changedOnlineStatusClient.setIsOnline(tempClientObject.isIsOnline());
}
model.addElement(changedOnlineStatusClient);
}
}
else{
System.out.println(tempClientObject.getUserName() + " is OFFLINE");
model.clear();
for (Iterator<Map.Entry<ClientObject,ImageIcon>> iter = labelIconList.entrySet().iterator(); iter.hasNext();) {
Map.Entry<ClientObject,ImageIcon> pairs = iter.next();
ClientObject changedOnlineStatusClient = (ClientObject) pairs.getKey();
if(changedOnlineStatusClient.getUserName().equalsIgnoreCase(tempClientObject.getUserName())){
changedOnlineStatusClient.setIsOnline(tempClientObject.isIsOnline());
}
model.addElement(changedOnlineStatusClient);
}
}
}
我可以保证逻辑系统工作正常。(如果它们在后台正常工作,我可以检查这些操作)。唯一的问题是有时连接到服务器 JList 的客户端看起来是空白的,即使它在模型中添加了元素。我会感谢每一个答案。无论如何谢谢