java - 如果为同一个 JButton 注册了 2 个 Action 监听器,则在特定条件下阻止执行 listener2

标签 java swing awt actionlistener

我有一个 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/

相关文章:

java.lang.ClassNotFoundException : org. jooq.util.JavaGenerator 异常

java - setDataVector - javax.swing.Table

java - 从 SPARQL 结果中的文字中删除数据类型

java - 查找 Java JButton 数组的索引

java - 检查矩形是否与文本相交

java - 向下转换 Graphics 实例 - 为什么允许这样做?

java - Java WebStart 导致 Naming.lookup 失败

java - 更改另一个类中 JLabel 的文本 (Java)

来自另一个类的 Java setText JLabel

java - 在 JTextPane 中定位图像(就像使用 setBounds 在 JFrame 中定位 JPanel)