在运行时Swing验证Event Dispatch Thread上的代码 [英] Swing verify code on Event Dispatch Thread at runtime

查看:135
本文介绍了在运行时Swing验证Event Dispatch Thread上的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在任何用于验证在事件调度线程上调用Swing组件上调用的方法的代码库?编写一些用于执行此操作的基本代码可能不会太困难,但我确信有其他人处理的边缘情况。我在运行时正在寻找这个,而不是单元测试。

Are there any libraries that instrument code to verify that methods called on Swing components are called on the Event Dispatch Thread? It probably wouldn't be too difficult to write some basic code for doing this, but I'm sure there are edge cases and whatnot that other people have handled. I'm looking for this at runtime though, not for unit tests.

推荐答案

FEST 框架有一个工具来检测EDT的Swing使用情况。它基本上是您安装的RepaintManager。该框架面向测试,但RepaintManager可以在部署时使用。

The FEST framework has a tool to detect Swing usage off the EDT. It's basically a RepaintManager that you install. The framework is oriented towards testing, but the RepaintManager can be used at deployment time.

  • See FEST - Swing's Event Dispatch Thread

或者,要检查所有方法(如getter和setter)只能在EDT上访问,可以使用AspectJ和加载时编织来添加SwingUtilities.isDisaptchThread()建议你的swing组件(以及JDK Swing组件)上的每个方法。

Alternatively, to check all methods such as getters and setters for access only on the EDT, you can use AspectJ and load-time weaving to add the SwingUtilities.isDisaptchThread() advice to each method on your swing components (and the JDK Swing components.)

@Aspect
public class EDTCheck {

    @Pointcut("call (* javax.swing..*+.*(..)) || " +
              "call (javax.swing..*+.new(..))")
    public void swingMethods() {}

    @Pointcut("call (* com.mystuff.swing..*+.*(..)) || " +
              "call (com.mystuff.swing..*+.new(..))")
    public void mySwingMethods() {}


    @Pointcut("call (* javax.swing..*+.add*Listener(..)) || " +
              "call (* javax.swing..*+.remove*Listener(..)) || " +
              "call (void javax.swing.JComponent+.setText(java.lang.String))")
    public void safeMethods() {}

    @Before("(swingMethods() || mySwingMethods()) && !safeMethods()")
    public void checkCallingThread(JoinPoint.StaticPart thisJoinPointStatic) {
        if(!SwingUtilities.isDispatchThread()) {
            System.out.println(
                    "Swing single thread rule violation: " 
                    + thisJoinPointStatic);
            Thread.dumpStack();
            // or you might throw an unchecked exception
        }
    }

}

(稍微修改了文章 - 添加了mySwingMethods切入点,并使用了SwingUtiliites.isDispatchThread()。实际上它与EventQueue.isDispatchThread()相同,但抽象更清晰。)

(Slightly modified from the article - added mySwingMethods pointcut, and use SwingUtiliites.isDispatchThread(). In practice it is the same as EventQueue.isDispatchThread() but the abstraction is cleaner.)

  • See Using AspectJ to detect violations of the Swing Single-Thread Rule

这篇关于在运行时Swing验证Event Dispatch Thread上的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆