单击3次后,Java将从按钮中删除侦听器

And*_*art -2 java swing action button listener

所以我想在按下按钮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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

JB *_*zet 5

该getActionListeners()方法返回按钮的所有侦听器.他们不是所有的例子ConfusedListener.我们唯一确定的事情就是它们的实例ActionListener.这就是你的代码无法编译的原因.

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

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