所以我想在按鈕被按下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