I know that JList
doesn't support ActionListeners
as said here , but I need to implement a list that keeps changing in the frame when new sockets connect to the server. So my question: What is the best way to implement this list?
DefaultListModel<String> data = new DefaultListModel<>(); //defaultlistModel
/**
adding data to jlist **/
data.addElement("new element");
jList1.setModel(data);
/**action listner on data(defaultlistModel) will be called when the list is changed*/
public void addlistner(){
data.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void intervalRemoved(ListDataEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void contentsChanged(ListDataEvent e) {
System.out.println("added"+e.getIndex1());
}
});
}
you cant do that with a jlist
. but its possible with defaultListModel
whenever you need to add data to the jlist . you should add your element to the defaultlistmodel
and then set the model in to the jlist
. and you can then write a listner to get called on changing properties in defaultListModel
. take a look at my code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.