[英]How to capture button click if more than one button in AspectJ?
我想知道如果有多個按鈕,我們是否可以捕獲點擊了哪個按鈕。
在這個例子中,我們可以達到//執行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
}
}
我不相信AspectJ是這項任務的正確技術。
我建議只為每個按鈕使用一個單獨的ActionListener
,或者使用ActionEvent
的getSource()
方法找到激活的按鈕。
但是,如果您喜歡使用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..
}
唯一的解決方案是執行運行時檢查,因為兩個JButton
對象的靜態簽名是相似的。
我在切入點中聲明了一個if()
條件。 這要求@Pointcut
注釋方法是一個公共靜態方法並返回一個布爾值。
嘗試這個:
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.