I have a recurring problem when I have a JList that I want to update with new content. I am using DefaultListModel, which provides methods for adding new content to the list, but when using these methods, I found that some portion of calls result in a completely empty JList. Regardless of whether the update works, it is random and is not related to the data being sent.
Below is a simple program that demonstrates the problem. It simply generates a size list for updating the JList, but when launched, the contents of the list appear and disappear, seemingly in random order.
As far as I can tell, I am following the right API for this, but I assume that something fundamental is missing me.
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.
source
share