我在做點擊遊戲程序。用戶必須鍵入時間限制(以秒爲單位)。如果該值爲正,則點擊按鈕將被啓用。當時間用完時,點擊按鈕將被禁用。這是我當前的代碼部分: 我似乎無法使用)從的setInterval(返回的值,禁用我點擊按鈕計時器命中0如何在定時器倒計時後禁用JButton爲0
public void actionPerformed(ActionEvent a) {
if (a.getSource()==startButton){
try{
String sec = timeField.getText();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(sec);
if(interval > 0){
timeLeft.setText("Time left: " + sec);
timeLeft.setText("Start!");
clickButton.setEnabled(false);
if(setInterval() > 0){
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timeLeft.setText("Time left: " + String.valueOf(setInterval()));
}
}, delay, period);
clickButton.setEnabled(true);
}else{
System.out.print(String.valueOf(setInterval()));
clickButton.setEnabled(false);
}
} else {
JOptionPane.showMessageDialog(null, "Error! Please enter postivie Interger! ", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Error! Please enter Integer! ", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if(a.getSource()==clickButton)
{
clickCOunter++;
clickLabel.setText("Clicks: " + clickCOunter);
}
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
此行是否按預期重複執行? timeLeft.setText(「Time left:」+ String.valueOf(setInterval())); – 2015-02-09 08:04:50
是的,它作爲一個計時器倒計時 – Hunter6310 2015-02-09 08:10:24