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;
}
}
});
添加回答
舉報