1.Consider my code is on some line of a JPanel that I have, am I automatically on EDT?
2.Same question for all other classes which are not belong to GUI, JPanels or other view classes, simple logical class.
3.If I have JPanel which I'm playing music while being in it, should the music run on event dispatch thread or on other thread which is not EDT (for not blocking the GUI, although I didn't feel any problem with running it from EDT)?
Note: I want a general rule how to know it without using the SwingUtilities.isEventDispatchThread()
Thanks
The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue.
Since Swing is not thread-safe by design, it's designer did provide couple of utility methods in SwingUtilities class to update any Swing component from a thread other thread Event Dispatcher Thread. You can use invokeAndWait() and invokeLater() to update a Swing component from any arbitrary thread.
An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.
Many important methods of Swing components are explicitly documented as threadsafe. These include the JComponent repaint() and revalidate() methods, many methods of Swing text components, and all listener add and remove methods.
If code running outside the EDT calls a method defined in a GUI class, that code will not be run on the EDT but in the calling thread.
If code running in the EDT calls code defined in a non-GUI class, that code will run on the EDT.
The rule is that if you're not creating a different thread, the method you're calling will run on the thread the calling code is running from – threads do not correspond to what classes methods are defined in.
Methods that will run on the EDT are event listeners, when they're called by Swing – not by you. (They still might be if you're calling them from the EDT though.)
Also, any code inside the Runnable.run()
method passed to SwingUtilities.invokeLater()
and invokeAndWait()
is also run on the EDT.
Any normal methods you call from the EDT will run on the EDT.
Any code called from a Thread
you create (whether using threads directly, or ExecutorService
, or SwingWorker.doInBackground()
) is not on the EDT. Your program's main()
method is also not on the EDT.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With