2

just a question about SwingUtilities.InvokeLater().

To my understanding, any time I update my Swing interface I need to call SwingUtilities.InvokeLater to get onto the EDT. Does this need to be done if I am attempting to update my GUI from a button listener, as they button events are already on the EDT?

i.e, would i have to..

    public void mouseClicked(MouseEvent e) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //GUI updates
        }
    });
}

or would I simply be able to...

        public void mouseClicked(MouseEvent e) {
   //GUI updates        
}

Furthermore, Does the same logic apply if I am calling a method on an object that will update the GUI?

2 Answers2

2

any time I update my Swing interface I need to call SwingUtilities.InvokeLater to get onto the EDT

Correct. This includes any time you update the model of the component, since this will also result in the repainting of the component.

Does this need to be done if I am attempting to update my GUI from a button listener, as they button events are already on the EDT?

Again correct. Since the code is automatically invoked on the EDT you do not need to manually add it to the EDT using the invokeLater().

You typically use the SwingUtilities.invokeLater() if your code is executing on a separate Thread and part of that logic needs to update a GUI component.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

Updating this message : Swing event handling code runs on a special thread known as the event dispatch thread. So all of the component(button, checkbox, radio button etc.,) actions are handled on EDT. So no need to have SwingUtilities.invokeLater() inside your button action as it always runs on EDT.

Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.

So if you are planning to perform a long running task that could affect a GUI inside an action then better go for Worker Threads or Background Threads.

SwingWorker has doInBackground(), done() and process() methods to handle the long running tasks well without impacting the GUI.

Go through below links to get more info Why does SwingUtilities.invokeLater() cause JButton to freeze?

What does SwingUtilities.invokeLater do?

https://www.javacodegeeks.com/2012/12/multi-threading-in-java-swing-with-swingworker.html

  • 1
    (1-) No you do not need the invokeLater() in the ActionListener. All Swing listener code IS executed on the Event Dispatch Thread (EDT) automatically. if you are invoking long running code you need to create a separate Thread in the ActionListener to prevent the GUI from freezing. – camickr Oct 26 '18 at 14:47