4

我想知道如果有多个按钮,我们是否可以捕获单击了哪个按钮。

在这个例子中,我们可以使用 joinPoints 达到 //do something1 和 //do something2 部分吗?

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
   }

}

4

2 回答 2

1

I don't believe AspectJ is the right technology for this task.

I recommend to just use a separate ActionListener for each button, or find the activated button with the ActionEvent's getSource() method.

However, if you like do it with AspectJ, here's a solution:

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.

I have declared an if() condition in the pointcut. This requires the @Pointcut annotated method to be a public static method and return a boolean value.

于 2010-05-30T20:19:41.050 回答
0

尝试这个:

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
        }
    }
}
于 2010-05-30T19:04:33.393 回答