0
我最近學會了如何使用計時器java類,並創建了一個程序,使用計時器倒計時,並使用標籤顯示此倒計時。我的問題是,程序倒數了2而不是1.程序倒數減2,而不是1,我看不到任何邏輯錯誤
package test;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import static javax.swing.UIManager.get;
public class Test extends JFrame implements ActionListener{
//Declare Global Variable
int timerValGlobal = 25;
//Define components to add
JButton startTimer = new JButton("Start Timer");
JButton exitButton = new JButton("Exit");
JLabel time = new JLabel();
Timer timer = new Timer(1000, this);
//Define panels
JPanel pane = new JPanel();
JPanel exitPane = new JPanel();
public Test(){
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Add buttons to panels
pane.add(startTimer);
pane.add(time);
exitPane.add(exitButton);
//Add panels to form;
add(pane, BorderLayout.NORTH);
add(exitPane, BorderLayout.SOUTH);
//Add ActionListeners to Buttons
startTimer.addActionListener(this);
exitButton.addActionListener(this);
timer.addActionListener(this);
}
public static void main(String[] args) {
Test t = new Test();
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == exitButton){
System.exit(0);
}
else if(source == startTimer){
timer.start();
}
else if (source == timer){
time.setText(String.valueOf(timerValGlobal));
timerValGlobal = timerValGlobal - 1;
if(timerValGlobal == 0){
timer.stop();
timerValGlobal = 25;
}
}
}
}
非常感謝。我仍然在接觸語言,像這樣的小事情是我生命中的禍根。這非常有幫助,謝謝。 –