Search code examples
javamultithreadingswingevent-dispatch-threadcode-duplication

When and Where to call EventQueue.invokeLater() method


I'm totally fresh about threading and GUIs, therefore I couldn't figure out exactly where to call this EventQueue.invokeLater() method.

Am I supposed to call it in every event listeners and something else? What are those "things" to call this method? If so, is there any alternative way to call-once-apply-everywhere method so that It won't take bunch of lines to tuck them to the Event dispatch thread?

Thank you.


Solution

  • therefore I couldn't figure out exactly where to call this EventQueue.invokeLater() method.

    Swing components need to be updated on the EDT so you would only use invokeLater(...) if you have code executing in a separate Thread and you want to update a GUI component.

    Read the section from the Swing tutorial on Concurrency for more information.

    As a general rule, unless you are using Threads, you only need to use this method when you create your GUI. Take a look at the FrameDemo from the section in the Swing tutorial on How to Make Frames for a simple example to get you started.

    Am I supposed to call it in every event listeners?

    No!

    All code in an event handler already executes on the Event Dispatch Thread (EDT)so you don't need to invoke this method.