How to capture button click if multiple buttons in AspectJ?

I wonder if we can fix which button is pressed if there are several buttons.

In this example, can we achieve // ​​do something 1 and // do something 2 parts with 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 } 

}

+4
source share
2 answers

I do not believe that AspectJ is the right technology for this task.

I recommend simply using a separate ActionListener for each button or finding the activated button using the ActionEvent getSource() method.

However, if you like to do this with AspectJ, here is the 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 run a run-time check because the static signatures are the same for both JButton objects.

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

+1
source

Try the following:

 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 } } } 
0
source

Source: https://habr.com/ru/post/1311361/


All Articles