Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

swing - Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?

I know that by using this method, the runnable parameter is submitted to the system EventQueue. But should all GUI updates be done this using this method? I mean, if i want to say, change a text of JButton, should i use something like this:

java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
         jButton1.setText("changed text");
      }
});

If i should use this approach, any pattern we can use to avoid this repetitive code?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...