Java Reference
In-Depth Information
DefaultListModel<String> listModel = new DefaultListModel<>();
COMPONENT.setModel(listModel);
getContentPane().add(COMPONENT);
pack();
setSize(300,500);
setVisible(true);
for (int t = 0; t < 16; t++) {
SwingUtilities.invokeLater(new CountingTask());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() { new MultiThreadedFrame(); }
});
}
}
The fact that you must ensure all UI updating code is run on the EDT might seem like an annoying
aspect of GUI programming at first, but there is a silver lining that relates to event listeners. Because
the EDT is responsible for catching user-interface events and also passes these to any event listen-
ers, any code that you execute inside an event listener will be run inside the EDT. This means that
you do not need to use invokeLater , for instance, when running code inside the actionPerformed
method of an ActionListener for a button, which, luckily, will also contain the multitude of UI‐
related code.
However, since this code is executed in the EDT, this means that, while the EDT is busy executing
the event listeners, the event loop will block until all event listeners have finished what they need to
do. Subsequent events will thus need to wait until they are handled, and since this can involve any-
thing from button clicks to window resizes, this can quickly lead to unresponsive, sluggish interfaces
when you stick too much calculation‐heavy code in your event listeners. Again, this is illustrated
with a simple example. Imagine you come up with the following beautiful progress‐tracking inter-
face to wrap around some heavy‐duty code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class ProgressTrackingFrame extends JFrame implements ActionListener {
private boolean isRunning = false;
private final JProgressBar bar = new JProgressBar(0, 100);
private final JButton btn = new JButton("Start Calculation");
public ProgressTrackingFrame() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Progress Tracker");
setLayout(new FlowLayout());
btn.addActionListener(this);
Search WWH ::




Custom Search