I have a recurring problem where I have a JList which I wish to update with new contents. I’m using a DefaultListModel which provides methods for adding new content to the list but when using these methods I find that some proportion of the calls result in a completely blank JList. Whether or not the update works seems to be random, and not related to the data which is sent.
Below is a simple program which demonstrates the problem. It simply generates a list of an increasing size to update a JList, but when run the list contents appear and disappear seemingly at random.
As far as I can tell I’m following the correct API to do this, but I guess there must be something fundamental I’m missing.
import java.awt.BorderLayout;
import javax.swing.*;
public class ListUpdateTest extends JPanel {
private JList list;
private DefaultListModel model;
public ListUpdateTest () {
model = new DefaultListModel();
list = new JList(model);
setLayout(new BorderLayout());
add(new JScrollPane(list),BorderLayout.CENTER);
new UpdateRunner();
}
public void updateList (String [] entries) {
model.removeAllElements();
for (int i=0;i<entries.length;i++) {
model.addElement(entries[i]);
}
}
private class UpdateRunner implements Runnable {
public UpdateRunner () {
Thread t = new Thread(this);
t.start();
}
public void run() {
while (true) {
int entryCount = model.size()+1;
System.out.println("Should be "+entryCount+" entries");
String [] entries = new String [entryCount];
for (int i=0;i<entries.length;i++) {
entries[i] = "Entry "+i;
}
updateList(entries);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {}
}
}
}
public static void main (String [] args) {
JDialog dialog = new JDialog();
dialog.setContentPane(new ListUpdateTest());
dialog.setSize(200,400);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true);
System.exit(0);
}
}
Any pointers would be very welcome.
Look at this code:
Implemented by SwingWorker. Works smooth.