Dispatch Thread Event Handling

I have a question about "Event Dispatch Thread". I have a Main class, which is also a JFrame. It initializes the remaining components of the code, some of which do not include Swing, and some of them are executed. Is it enough to just initialize the main class using EDT, like this? ...

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

This way everything will work in the event dispatcher thread.

+3
source share
4 answers

This is usually enough until you start using background threads for computing, data collection, etc. Then you need to be careful to make sure you are on the EDT before modifying the swing component or its model.

, EDT :

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

, . SwingWorker , EDT

+6

. , , , , Swing, ( ). invokeLater, .

+2

Sun. Swing Concurrency , .

+2
source

Devon_C_Miller the correct answer. I just want to specify a shortcut to call the event dispatch thread.

This is how I run all of my Swing applications.

import javax.swing.SwingUtilities;

import com.ggl.source.search.model.SourceSearchModel;
import com.ggl.source.search.view.SourceSearchFrame;

public class SourceSearch implements Runnable {

    @Override
    public void run() {
        new SourceSearchFrame(new SourceSearchModel());

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new SourceSearch());
    }

}

You can copy this into every Swing project simply by changing the names.

+1
source

Source: https://habr.com/ru/post/1739197/


All Articles