OK so I have a JList and the content is provided with an array. I know how to add elements to an array but I want to know how to refresh a JList... or is it even possible? I
One good approach is to create a ListModel to manage the data for you and handle updates.
Something like:
DefaultListModel listModel=new DefaultListModel();
for (int i=0; i<data.length; i++) {
listModel.addElement(data[i]);
}
list=new JList(listModel);
Then you can simply make changes via the list model e.g.
listModel.addElement("New item");
listModel.removeElementAt(1); // remove the element at position 1
You just need to supply your own ListModel:
class MyModel extends AbstractListModel {
private String[] items;
public MyModel(String[] items) {
this.items = items;
}
@Override
public Object getElementAt(int index) {
return items[index];
}
@Override
public int getSize() {
return items.length;
}
public void update() {
this.fireContentsChanged(this, 0, items.length - 1);
}
}
After sorting items, just call update
.