所以我想在按钮被按下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循环,我没有任何关于如何去做的想法。
工作了魅力十分感谢:) – AndyOHart