2013-11-21 48 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