1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
因?yàn)樵?b1.addActionListener 上你設(shè)置了 boolean start = true; 這意味著每當(dāng)你回到你的 actionPerformed 監(jiān)聽(tīng)器時(shí),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;類(lèi)后并在默認(rèn)構(gòu)造函數(shù)中初始化start=true;,您可以在代碼中使用 start 變量。
或者簡(jiǎn)單的 例子
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;
}
}
});
添加回答
舉報(bào)