计时器启动后,可切换按钮不起作用

时间:2019-06-24 09:45:54

标签: java swing

我正在尝试创建一个可切换的按钮,以启动和停止倒数计时器。它会启动计时器,但不会停止。我是Java和swing的初学者,有人可以帮忙吗? 这是一些代码:

private static Timer timer;
timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        l1.setText(Integer.toString(timeLeft / 60) + ":" + Integer.toString(timeLeft % 60));
        timeLeft--;
        if (timeLeft == 0) {
            boolean rest = false;
            if (rest) {
                timeLeft = workTime;
                JOptionPane.showMessageDialog(null, "Times Up!");
                rest = false;
            } else {
                timeLeft = restTime;
                JOptionPane.showMessageDialog(null, "Times Up!");
                rest = true;
            }
        }
    }
});
b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        boolean start = true;
        if (start == true){
            timer.start();
            b1.setText("stop");
            start = false;
        } else if (start == false){
            timer.stop(); //the part that doesn't work
            b1.setText("start");
            start = true;
        }
    }
});

这不是确切的代码,而是重要的部分

1 个答案:

答案 0 :(得分:0)

因为在b1.addActionListener上设置了boolean start = true;这意味着每当您返回到actionPerformed侦听器时,总是需要start = true在actionPerformed之外进行声明和初始化。

b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        boolean start = true;
        if (start == true){
            timer.start();
            b1.setText("stop");
            start = false;
        } else if (start == false){
            timer.stop(); //the part that doesn't work
            b1.setText("start");
            start = true;
        }
    }
});

建议:您还可以在类后声明boolean start;,并在默认构造函数start=true;进行初始化,并可以在代码中使用start变量。

或简单地 示例

private static Timer timer;
boolean start = true;
boolean rest = false;
timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        l1.setText(Integer.toString(timeLeft / 60) + ":" + Integer.toString(timeLeft % 60));
        timeLeft--;
        if (timeLeft == 0) {
            if (rest) {
                timeLeft = workTime;
                JOptionPane.showMessageDialog(null, "Times Up!");
                rest = false;
            } else {
                timeLeft = restTime;
                JOptionPane.showMessageDialog(null, "Times Up!");
                rest = true;
            }
        }
    }
});
b1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        if (start == true){
            timer.start();
            b1.setText("stop");
            start = false;
        } else if (start == false){
            timer.stop(); //the part that doesn't work
            b1.setText("start");
            start = true;
        }
    }
});