简体   繁体   中英

Forcing EDT Thread for Swing Libraries

All GUI related code should only be executed from the EDT . In Android development, something like this seems to be enforced kind of so you'll get an exception if you do eg make a network call in the main thread. However, for developing Java desktop application, there is no such thing. It is easy to forget about the EDT and still executing GUI code in another thread. This can cause weird glitches/bugs because Swing is not thread-safe . Is there a way to strongly enforce the usage of the EDT for every GUI code by default similar to how Android is more strict? I do not want to manually check everything and instead get an exception if the EDT usage recommendation is violated. I'm using IntelliJ IDEA .

In terms of Java code, something like the following could be inserted automatically for every Swing library method:

if(!SwingUtilities.isEventDispatchThread())
{
    throw new IllegalStateException("EDT property violated");
}

Any way to get this?

There is a ThreadCheckingRepaintManager, see here: ThreadCheckingRepaintManager

You can use it like this:

public static void main(String args[]) {
        RepaintManager.setCurrentManager(new ThreadCheckingRepaintManager(true));
        //Create your UI here
    }

Now you will get an info in the console whenever there is a EDT problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM