Search code examples
javamultithreadingswinginvokelaterawt-eventqueue

EventQueue.invokeLater in Java Swing


I am trying to understand the real purpose of this thread. I have read books , articles ,but didn't undrstand clearly what EventQueue thread is responsible for. I have seen a lot of examples, sometimes this is used, sometimes not. As I understood this thread is responsible for ALL GUI OPERATIONS, such creating windows, components, calling native functions from OS API and other stuff. So every time I change some part of GUI I should pass this action to queue. So using queue application has two threads by default main and event dispatching thread. So I all bussines logic should be performed in main thread (or create new thread from main) and all gui operations in EventQueue(for example adding new item to the table, changing text in label updating list). Futhermore I should create instance of main windows (class extends jframe) in EventQueue ?

Am I right ? If not please explain. Thanks everyone in advance.


Solution

  • It sounds like you've got the gist of it, yes. If your application is essentially "pure GUI" you can just do everything on the EDT (Event Dispatch Thread, which is the thread that runs whatever you pass to EventQueue.invokeLater), but you must create windows on the EDT which means your main() method must use EventQueue.invokeLater at least once.

    Because all listeners on GUI objects will be notified on the EDT, you do not need use EventQueue.invokeLater from your handlers, generally.