我目前正在使用Alexander Potochkin的AspectJ EDTChecker code(相关的代码在文章底部).
这段代码(据我对AspectJ的了解很少)抱怨Swing EDT中没有发生的任何JComponent方法调用或构造函数调用.
但是,以下内容仅针对JList构造函数,而不针对JFrame构造函数.谁能告诉我为什么?谢谢!
package testEDT;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
public class TestEDT{
JList list;
final JFrame frame;
public TestEDT() {
DefaultListModel dlm = new DefaultListModel();
list = new JList(dlm);
frame = new JFrame("TestEDT");
}
public static void main(String args[]) {
TestEDT t = new TestEDT();
t.frame.setVisible(true);
}
}
Alexander Potochkin的AspectJ代码:
package testEDT;
import javax.swing.*;
/**
* AspectJ code that checks for Swing component methods being executed OUTSIDE the Event-Dispatch-Thread.
*
* (For info on why this is bad, see: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html)
*
* From Alexander Potochkin's blog post here:
* http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html
*
*/
aspect EdtRuleChecker{
/** Flag for use */
private boolean isStressChecking = true;
/** defines any Swing method */
public pointcut anySwingMethods(JComponent c):
target(c) && call(* *(..));
/** defines thread-safe methods */
public pointcut threadSafeMethods():
call(* repaint(..)) ||
call(* revalidate()) ||
call(* invalidate()) ||
call(* getListeners(..)) ||
call(* add*Listener(..)) ||
call(* remove*Listener(..));
/** calls of any JComponent method, including subclasses */
before(JComponent c): anySwingMethods(c) &&
!threadSafeMethods() &&
!within(EdtRuleChecker) {
if ( !SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) {
System.err.println(thisJoinPoint.getSourceLocation());
System.err.println(thisJoinPoint.getSignature());
System.err.println();
}
}
/** calls of any JComponent constructor, including subclasses */
before(): call(JComponent+.new(..)) {
if (isStressChecking && !SwingUtilities.isEventDispatchThread()) {
System.err.println(thisJoinPoint.getSourceLocation());
System.err.println(thisJoinPoint.getSignature() + " *constructor*");
System.err.println();
}
}
}
解决方法:
JFrame不是JComponent的子类,但JList是.