Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?
Solution 1:
You only need to use invokeLater
when you want to update your UI from another thread that is not the UI thread (event dispatch thread).
Suppose you have a handler for a button-click and you want to change the text of a label when someone clicks the button. Then it's perfectly save to set the label text directly. This is possible because the handler for the button-click event runs in the UI thread.
Suppose, however, that on another button-click you start another thread that does some work and after this work is finished, you want to update the UI. Then you use invokeLater
. This method ensures that your UI update is executed on the UI thread.
So in a lot of cases, you do not need invokeLater
, you can simply do UI updates directly. If you're not sure, you can use isDispatchThread
to check whether your current code is running inside the event dispatch thread.
Solution 2:
You need to do this only if you're not already on the event dispatch thread. Unless you've started new threads or executed code from the main thread all your code probably already runs from the event dispatch thread making this unnecessary. For example, all the UI event handlers are called on the event dispatch thread so you would not need to do that for code called from there.
Solution 3:
Instead of truly avoiding "repetitive" (java people would probably say, readable code without many secrets) you could use Eclipse's templates feature. i have it set to expand the two letters "il" to the following block:
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
// do something.
} catch (Exception e) {
e.printStackTrace();
}
}
});
Apparently this dispatch queue design is not only recommended, it's basically required. This is perhaps the noisiest way I've ever seen in any language of pushing a lambda off into a message queue. But there it is. This is java. And in Java's defence, it's certainly obvious from the above exactly what's going on. I do resent the amount of typing, but the only thing I can think of that would avoid it is C preprocessor Macros, and I bet Java people don't like using those. Code expansion via templates is more readable, supportable, and doesn't involve any black magic.