我有一个 JButton,为它注册了两个 Action 监听器。 Listener1
会先执行,因为它是先注册的。
所以,我需要的是,如果 Listener1
中的条件匹配,则不应执行 Listener2
的代码。
如果 Listener1 中的条件匹配,请您帮助我如何防止执行 Listener2。
JButton jbtn=new JButton();
jbtn.addActionListener(new ActionListener() {
//Listener1
public void actionPerformed(ActionEvent e)
{
if(condition==true){
//do not execute the code of listner2
//stop further executeion of current action
}
}
});
jbtn.addActionListener(new ActionListener() {
//Listener2
public void actionPerformed(ActionEvent e)
{
//some code
}
});
最佳答案
在我看来,您可能把事情复杂化了。为什么不简单地使用一个 ActionListener 或 AbstractAction 并将 if block 嵌套在其中:
jbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(condition) { // no need for the == true part!
myMethod1();
} else { // condition is false
myMethod2();
}
}
});
关于java - 如果为同一个 JButton 注册了 2 个 Action 监听器,则在特定条件下阻止执行 listener2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493398/