Reputation: 97
In my program there are 4 threads that addElemets to a model of a jlist at the same time. This causes jlist to blink, throw excpetions or even crash, because of the too many updates or repaints.
I tried to put some delay that fixed my problem but I was losing to much precious time.
What can I do?
this code simulates my problem:
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<4; i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int o=0; o<2000; o++){
model.addElement("add");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}).start();
}
}
}).start();
Upvotes: 1
Views: 121
Reputation: 14863
To avoid too many refresh/repaint you have to do the model updates in the background threads and to copy once into the swing model in the EDT with the technique previously exposed. I suggest to do not use the DefaultListModel but a custom made to dispose of addAll().
SwingUtilities.invokeLater(new Runnable() {
public void run() {
listModel.addAll( backgroundModel ); // only one fireDataChanged() fired
}
});
Upvotes: 1
Reputation: 32391
The model.addElement("add"); should be something like this:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
listModel.addElement("add");
}
});
This way you make sure that the elements are added under the EDT and not in some random thread.
Upvotes: 2
Reputation: 18819
GUI manipulations should only be performed on the event dispatch thread. Even if you have created many threads, do your non-GUI work on them n fire an actionCommand (or something similar) to manipulate GUI aspects.
You will get to read this warning many times in the Java Docs: Swing components are not thread safe
Upvotes: 1