Handling the Event Dispatch Thread

♀尐吖头ヾ 提交于 2019-11-30 10:22:56

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

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.

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.

Gilbert Le Blanc

Devon_C_Miller's answer is correct. I just want to point out a shortcut to invoking the event dispatch thread.

Here's how I start 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 to every Swing project, just by changing the names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!