tags:

views:

146

answers:

3

Hi,

I have a question about the 'Event Descriptor Thread'. I have a Main class that is also a JFrame. It initialises the rest of the components in the code, some of them do not involve Swing and some of them do. Is it enough to simply initialise the Main class using the EDT like this?...

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Main();
        }
    });
}

This way everything would run on the Event Dispatcher thread.

+2  A: 

This is the way to go. The only thing you should be careful about is if a listener that you register with the Swing components will spawn a new Thread (often for carrying out some long computation). Such new threads will need to use invokeLater if they are to carry out GUI operations.

Itay
+4  A: 

That is generally sufficient until you start making use of background threads for calculations, data acquisition, etc. Then you need to start being careful to verify that you are on the EDT prior to altering a swing component or its model.

You can test whether you're executing on the EDT with:

    if (SwingUtilities.isEventDispatchThread()) {
        // Yes, manipulate swing components
    } else {
        // No, use invokeLater() to schedule work on the EDT
    }

Also, see the SwingWorker class for details on how to hand off work to a background thread and process results on the EDT

Devon_C_Miller
I'm sure I'll need that for future reference. For now my app is single-threaded so I should be fine. Thank you!
waitinforatrain
+2  A: 

That is the way all the examples from the Sun tutorial work. Read the section from the Swing tutorial on Concurrency for more information on why it is done this way.

camickr