简体   繁体   English

如果在AspectJ中有多个按钮,如何捕获按钮?

[英]How to capture button click if more than one button in AspectJ?

I wonder if we can capture that which button is clicked if there are more than one button. 我想知道如果有多个按钮,我们是否可以捕获点击了哪个按钮。

On this example, can we reach //do something1 and //do something2 parts with joinPoints? 在这个例子中,我们可以达到//执行something1和//使用joinPoints执行某些操作吗?

public class Test {

    public Test() {
        JButton j1 = new JButton("button1");
        j1.addActionListener(this);

        JButton j2 = new JButton("button2");
        j2.addActionListener(this); 
    }

    public void actionPerformed(ActionEvent e)
   {
      //if the button1 clicked 
           //do something1
      //if the button2 clicked 
           //do something2
   }

} }

I don't believe AspectJ is the right technology for this task. 我不相信AspectJ是这项任务的正确技术。

I recommend to just use a separate ActionListener for each button, or find the activated button with the ActionEvent 's getSource() method. 我建议只为每个按钮使用一个单独的ActionListener ,或者使用ActionEventgetSource()方法找到激活的按钮。

However, if you like do it with AspectJ, here's a solution: 但是,如果您喜欢使用AspectJ,这是一个解决方案:

public static JButton j1;

@Pointcut("execution(* *.actionPerformed(*)) && args(actionEvent) && if()")
public static boolean button1Pointcut(ActionEvent actionEvent) {
    return (actionEvent.getSource() == j1);
}

@Before("button1Pointcut(actionEvent)")
public void beforeButton1Pointcut(ActionEvent actionEvent) {
    // logic before the actionPerformed() method is executed for the j1 button..
}

The only solution is to execute a runtime check, since the static signatures are similar for both JButton objects. 唯一的解决方案是执行运行时检查,因为两个JButton对象的静态签名是相似的。

I have declared an if() condition in the pointcut. 我在切入点中声明了一个if()条件。 This requires the @Pointcut annotated method to be a public static method and return a boolean value. 这要求@Pointcut注释方法是一个公共静态方法并返回一个布尔值。

Try this: 尝试这个:

public class Test {
    JButton j1;
    JButton j2;

    public Test() {
        //...
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == j1) {
            // do sth
        }

        if (e.getSource() == j2) {
            // do sth
        }
    }
}

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

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