按钮点击计数器无法正常运行

时间:2017-02-05 09:31:12

标签: java swing

我已经构建了一个可以计算点击次数的GUI。问题是,当我按下重置按钮然后单击增量时,它会不断添加到旧计数器。感谢您的帮助。

private class MyEventHandler implements ActionListener
{
    private JTextField counter;
    private int clicks;

    public MyEventHandler(JTextField counter)
    {
        this.counter = counter;
    }

    @Override
    public void actionPerformed(ActionEvent event) 
    {
        if (event.getSource() == increment)
        {   
            clicks++;
            counter.setText("Number of increments: " + clicks);

        }
        else if (event.getSource() == reset)
        {
            clicks = 0;
            counter.setText("Number of increments: " + clicks);
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您需要将Like = YES Like = true Like = 1 变量作为clicks。静态变量在所有对象之间共享,因此static将在clicks时为每个事件处理程序重置getSource() == reset

您可以为两个按钮提供通用动作侦听器:

MyEventHandler meh = new MyEventHandler();
increment.setActionListener(meh);
reset.setActionListener(meh);