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的客户端看起来空白时,即使它将元素添加到模型中,有时也只会出现问题。我会很感激每一个答案。无论如何,谢谢
答案 0 :(得分:1)
只评论,而非答案
不需要一维JList
if(value instanceof ClientObject){
因为来自
的Object
getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean hasFocus) {
返回相同的值,然后测试此值if == or equeals
...
答案 1 :(得分:0)
首先感谢您的所有回复。另一方面,我在必须更新时创建新模型时纠正了我的问题。所以代码段是这样的;
DefaultListModel tempModel = new DefaultListModel();
// add or remove elements from tempModel
buddyList.setModel( tempModel );
我不确定它是否是唯一正确的方法,但至少它是有效的。
答案 2 :(得分:-1)
调用model.fireContentsChanged()
方法。