2013-11-21 46 views
-2

所以我想在按钮被按下3次之后从监听器中删除监听器。 到目前为止,我有这个Java在3次单击后从按钮中删除监听器

class Q5 
{ 
JFrame frame; 
JButton button; 
int clickCount = 0; 

public static void main (String[] args) 
{ 
    Q5 example = new Q5(); 
    example.go(); 
} 

public void go() 
{ 
    frame = new JFrame(); 

    button = new JButton ("Should I do it"); 
    button.addActionListener(new ButtonPressListener()); 
    button.addActionListener(new AngelListener()); 
    button.addActionListener(new DevilListener()); 
    button.addActionListener(new ConfusedListener()); 



    frame.getContentPane().add(BorderLayout.CENTER, button); 
    frame.setVisible(true); 
    frame.setSize(400,150); 
    // set frame properties here 
} 

class ButtonPressListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     clickCount++; 
    } 
} 

class AngelListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     System.out.println("Don't do it, you might regret it!"); 
    } 
} 

class DevilListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     System.out.println("Go on, do it!"); 
    } 
} 

class ConfusedListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent event) 
    { 
     if(clickCount > 3) 
     { 
      for(ConfusedListener conf : button.getActionListeners()) 
      { 
       button.removeActionListener(conf); 
      } 
     } 
     else 
      System.out.println("I don't know!"); 
    } 
} 

我在线阅读是对循环做,就像我上面尝试的方式,但我得到一个类型不匹配。我能找到的大部分示例都是关于删除所有侦听器,但我只想从按钮中删除ConfusedListener。除了上面的for循环,我没有任何关于如何去做的想法。

回答

5

getActionListeners()方法返回按钮的所有听众将其删除。它们并不都是ConfusedListener的实例。我们唯一确定的事情是他们是ActionListener的实例。这就是为什么你的代码不能编译。

现在,为什么你需要一个循环来移除给定的监听器?您只需删除正在调用的ConfusedListener。所以,你只需要

public void actionPerformed(ActionEvent event) 
{ 
    if(clickCount > 3) 
    { 
     button.removeActionListener(this); 
    } 
    else 
     System.out.println("I don't know!"); 
} 
+0

工作了魅力十分感谢:) – AndyOHart

1

你可以尝试:

if(clickCount > 3) 
    { 
     for(ActionListener listener : button.getActionListeners()) 
     { 
      if (listener instanceOf ConfusedListener) { 
       button.removeActionListener(conf); 
      } 
     } 
    } 
    else 
     System.out.println("I don't know!"); 

你也可以加入,当它保存ConfusedListener的实例,并通过

button.removeActionListener(confusedListenerInstance); 
+0

感谢您的回答公认的答案真是棒极了:) – AndyOHart

1

只存储监听器本身的实例,并用它来除去正确的监听器:

final ConfusedListener confusedListener = new ConfusedListener(); 
button.addActionListener(confusedListener); 
button.removeActionListener(confusedListener); 

如果你是从去除ConfusedListener本身就是一种方法里面听者的只是通过this:但是

button.removeActionListener(this); 
+0

感谢您的回复,但接受的答案效果很好:) – AndyOHart