Java Swing - running on EDT
- Basically, every time you use a Swing component or a model of a Swing component, it must be done in the EDT. If you don't, no exception will be raised. It could work, but it could also not work, have erratic behavior, corrupted data, etc.
- Every Swing event listener is called in the EDT. Basically, except the main method, every line of code of a Swing application is executed in the EDT by default, unless you explicitely start a thread, use a SwingWorker, or something like that.
- yes.
- Tasks submitted to SwingUtilities.invokeLater() are executed in the same order as the order they were submitted.
- Internally, it uses SwingUtilities.invokeLater() or a similar method. The FutureTask doesn't have anything to do with Swing. It's the SwingWorker that ensures that its done method is executed in the EDT. The
doneEDT()
method has the following comment: Invokes done on the EDT.
A good rule is that all operations (access/updates/...) should happen on the EDT. There are a few exceptions mentioned in the javadoc (certain methods of certain classes), but they are so hard to remember that it is easier to stick to the 'do everything on the EDT' approach. Exceptions will not be raised (luckily, JavaFX fixed this shortcoming). You can use a custom
RepaintManager
to detect most of these violations: see this article.Everything triggered by the user is handled on the EDT. For example if the user clicks on a button, the
actionPerformed
of the correspondingAction
orActionListener
will be called on the EDT.Correct
The thing you schedule first will be executed first. The
invokeLater
call simply adds theRunnable
at the end of the queue. UsinginvokeLater
a second time a bit later will add this newRunnable
after the previously scheduledRunnable
.Take a look at the code for
doneEDT
private void doneEDT() { Runnable doDone = new Runnable() { public void run() { done(); } }; if (SwingUtilities.isEventDispatchThread()) { doDone.run(); } else { doSubmit.add(doDone); } }