1 回答
TA贡献1818条经验 获得超8个赞
因为在 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;
}
}
});
添加回答
举报