I have a convenience method to test out JPanels:
I'm not sure exactly which of these statements I should be putting within the inner class, and does it matter? Is it just the setVisible bit that will determine if user interactions will occur on the EDT?
All event dispatch in Swing occurs on the EDT. As a general rule, you should run all code that constructs and alters the state of Swing components only on the EDT. Also note that various Swing methods (particularly text component methods) that are, as of Java 1.6, documented as being thread safe are not actually so, and the mention of thread safety is removed from the documentation for Java 1.7.
Darryl Burke wrote:All event dispatch in Swing occurs on the EDT. As a general rule, you should run all code that constructs and alters the state of Swing components only on the EDT.
I would also add all code that queries the state of Swing components, like calling getText() on a text field.
Luigi, you can get away with creating your user interface before the EDT is started. In your example the call to SwingUtilities.invokeLater could have been omitted; the setVisible(true) method would cause the EDT to be started. However, as Darryl said, could does not mean should. Although I still go the lazy way and skip EventQueue.invokeLater* when constructing my GUIs a lot of the time.
*SwingUtilities.invokeLater delegates to EventQueue.invokeLater, as is also mentioned in the Javadocs.
Thanks. So really I should only ever call such a method from the EDT, or I should put everything in this method into the inner class, plus instantiating the JPanel I want to display. The latter could be a bit tricky if I'm subclassing JPanel, because I'd need to pass in a Class argument, rather than an instance of a panel.
Rob - thanks for the tip. I had a poke around in the JComponent.setVisible source code and it seems that the reValidate method that it calls checks whether it's being run in the EDT, and if not, adds itself.
Rob Spoor wrote:setVisible(true) method would cause the EDT to be started.
How and when the EDT is started may be platform dependent. Here's a SSCCE that demonstrates that the mere construction of a JPanel kicks off the EDT, on Windows at least.If you comment out new JPanel() the main thread terminates and the program exits before the Timer has a chance to trigger its actionPerformed.
Incidentally, I found that constructing a JComponentdoesn't kick off the EDT