简体   繁体   English

Swing库的强制EDT线程

[英]Forcing EDT Thread for Swing Libraries

All GUI related code should only be executed from the EDT . 所有与GUI相关的代码仅应从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. Android开发中,类似的事情似乎是强制执行的,因此,如果您在主线程中进行了网络调用等操作,您将获得异常。 However, for developing Java desktop application, there is no such thing. 但是,对于开发Java桌面应用程序,没有这种东西。 It is easy to forget about the EDT and still executing GUI code in another thread. 很容易忘记EDT并仍在另一个线程中执行GUI代码。 This can cause weird glitches/bugs because Swing is not thread-safe . 这可能会导致奇怪的故障/错误,因为Swing不是线程安全的 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? 有没有一种方法可以默认对每个GUI代码强加EDT的使用,类似于Android更加严格的方法? I do not want to manually check everything and instead get an exception if the EDT usage recommendation is violated. 我不想手动检查所有内容,而是在违反EDT使用建议的情况下得到异常。 I'm using IntelliJ IDEA . 我正在使用IntelliJ IDEA

In terms of Java code, something like the following could be inserted automatically for every Swing library method: 就Java代码而言,可以为每个Swing库方法自动插入以下内容:

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

Any way to get this? 有什么办法吗?

There is a ThreadCheckingRepaintManager, see here: ThreadCheckingRepaintManager 有一个ThreadCheckingRepaintManager,请参见此处: 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. 现在,只要有EDT问题,您都将在控制台中获得一条信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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