0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    All event _handlers_ are invoked in the event handler thread. So, if you write an action listener for a button, it's actionPerformed() method will be called in the event handler thread when the button is clicked. If the action of the button is something that won't take significant time, you can just call Swing methods directly from within actionPerformed(). No need to "invokeLater()" in that case. – Solomon Slow Sep 25 '14 at 17:35

2 Answers2

3

EventQueue manages a single GUI thread because it must rely on the host platform's GUI resources, which are also single-threaded. You can run non-GUI code on the initial thread, but you must synchronize access to any shared data yourself. SwingWorker, examined here, is a convenient alternative.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

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.

davmac
  • 20,150
  • 1
  • 40
  • 68
  • So for instance if I am creating JFrame in EDT, all other stuff like adding items to can be performed without passing action to the queue ? Because main frame was created in EDT, all future actions with it, also will be performed in EDT ? –  Sep 25 '14 at 16:46
  • As long as your 'other stuff' runs as a GUI callback, then yes, you're fine. – davmac Sep 26 '14 at 09:27