tags:

views:

46

answers:

2

Hi all,

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?

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
   }

}

A: 

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
        }
    }
}
Crozin
+1  A: 

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.

Espen