Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all Swing components run on the EDT by default?

I'm new to Java and after reading many articles about threads and swing I understood that all the invocations of Swing methods should be done on the EDT because Swing is not thread safe. however, I already wrote a couple of quite long Swing applications before reading about the EDT. and all of my applications ran quite fine. So my question is were my Swing applications running on the EDT by default or were they running on a different thread and i was just lucky not to have any issues with them? Like for example if I add a JButton to a JPanel or JFrame, or if I simply call a JTextField's Field.setText(), will these operations be running on the EDT by default or no? and if the answer is no, then do I have to explicitly send all my Swing component's methods implementations to run on the EDT by invoking SwingUtilities.invokeLater()

Thanks

like image 344
GamefanA Avatar asked Dec 20 '22 12:12

GamefanA


1 Answers

Remember objects don't live on threads, only execution of methods happens on a thread.

All action emerging (through listeners) from swing components automatically run on the EDT.

For instance a button you click, the onClicked() function will already run on the EDT so you don't need to do anything.

If you don't create any threads explicitly, your basic application will have a main thread and an EDT (and many other threads that you don't accidentally get your code executed on, until you start using extra frameworks).

The thing you have to do manually is construct the GUI on the EDT. As you can see here this can be done in your main thread as follows:

   SwingUtilities.invokeLater(new Runnable() { 
        public void run() {            
            MyWindow window = new MyWindow ();
            window.setVisible(true);
        }
    });

If you fail to use the EDT correctly. Everything will seem to work fine, but every now and then you can get very strange behavior (because two threads will be doing things instead of one).

So in summary you have to use invokeLater(), or in some exceptions invokeNow() in the following cases:

  1. Constructing Swing components from the main thread.
  2. Calling swing components from your personally created threads.
  3. Calling swing components from events on threads created by frameworks.

This question contains some tools that can help you automatically detect errors (not all though).

like image 146
Thirler Avatar answered Jan 04 '23 22:01

Thirler