我看不到您的问题。 Swing 与否,您只是在使用 Java 类。如果您可以将AspectJ 应用于其他Java 类,您也可以将其应用于Swing 类。试一试吧,一旦您了解了基本概念,使用 AspectJ 的 AOP 就会非常有趣。如果您有具体问题,我很乐意为您提供帮助。
更新:好的,我刚刚有一些空闲时间,并使用了一些sample code 为您编写了一个快速演示。
最小的 Swing 示例抛出两个 RuntimeExceptions,一个在创建主窗口期间,另一个在您单击弹出对话框中的“确定”时:
import java.awt.event.*;
import javax.swing.*;
public final class MinimalSwingApplication {
public static void main(String... aArgs) {
MinimalSwingApplication app = new MinimalSwingApplication();
app.buildAndDisplayGui();
}
private void buildAndDisplayGui() {
JFrame frame = new JFrame("Main window");
buildContent(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void buildContent(JFrame aFrame) {
JPanel panel = new JPanel();
panel.add(new JLabel("Hello"));
JButton ok = new JButton("Show pop-up dialog");
ok.addActionListener(new ShowDialog(aFrame));
panel.add(ok);
aFrame.getContentPane().add(panel);
throw new RuntimeException("Oops!");
}
private static final class ShowDialog implements ActionListener {
private JFrame fFrame;
ShowDialog(JFrame aFrame) {
fFrame = aFrame;
}
public void actionPerformed(ActionEvent aEvent) {
JOptionPane.showMessageDialog(fFrame, "I am the a pop-up dialog");
throw new RuntimeException("Something unexpected happened here");
}
}
}
记录异常的示例方面(使用 JDK 日志记录,但您可以轻松切换到 Log4J):
import java.util.logging.*;
public aspect SwingExceptionLogger {
static Logger logger = Logger.getLogger(SwingExceptionLogger.class.getName());
Object around() : execution(* MinimalSwingApplication..*(..)) {
try {
return proceed();
} catch (Exception e) {
logger.log(Level.WARNING, "Swing exception: " + e.getMessage());
return null;
}
}
}
启动应用程序和两次打开/关闭弹出对话框的示例输出:
10.11.2012 09:42:28 MinimalSwingApplication buildContent_aroundBody5$advice
WARNUNG: Swing exception: Oops!
10.11.2012 09:42:33 MinimalSwingApplication$ShowDialog actionPerformed_aroundBody1$advice
WARNUNG: Swing exception: Something unexpected happened here
10.11.2012 09:42:37 MinimalSwingApplication$ShowDialog actionPerformed_aroundBody1$advice
WARNUNG: Swing exception: Something unexpected happened here
如果你想要的话,你总是可以优化切入点,只记录来自 AWT/Swing 线程的内容。您也可以重新抛出异常而不是吞下它。随意尝试或询问。