Java Reference
In-Depth Information
You've already seen an important rule regarding the EDT, namely that all UI-related code should
be run inside this thread. The way to do so is simple, namely by using the SwingUtilities helper
class, which defines the following methods to help out with threading:
invokeLater(Runnable doRun) : Executes doRun.run() asynchronously on the event dis-
patching thread.
invokeAndWait(Runnable doRun) : Executes doRun.run() synchronously on the event dis-
patching thread, meaning that this method will wait until doRun.run() has completed.
isEventDispatchThread() : Returns true if the current thread is the event dispatching thread.
In almost all cases, you'll use the invokeLater method to wrap UI‐affecting code as follows:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// UI affecting code
}
});
One particular place where it is important to use this method is in the main method of your pro-
grams, as it is guaranteed there that you will not yet be in the EDT (but instead in the initial main
thread). Using SwingUtilities , you can rewrite the earlier example as follows:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class MultiThreadedFrame extends JFrame {
public static final int LENGTH = 100;
public static final JList<String> COMPONENT = new JList<>();
public class CountingTask implements Runnable {
public void run() {
for (int i = 1; i <= LENGTH; i++) {
// Add an item
((DefaultListModel<String>) COMPONENT.getModel()).clear();
((DefaultListModel<String>)
COMPONENT.getModel()).addElement("At: "+i);
// Force component repaint
COMPONENT.repaint();
COMPONENT.invalidate();
COMPONENT.repaint();
// Sleep for a little to give other threads a chance
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public MultiThreadedFrame() {
Search WWH ::




Custom Search