我为我创建的游戏制作计时器,但我很难重新启动计时器方法。它暂停计时器大约一秒然后继续计数,例如:如果计时器打开4,如果重置按钮被击中,计时器将暂停4秒钟然后恢复到5,6等等。无论如何解决这个问题?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends Panel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
Timer timer;
public MyTimer(){
MyTimer timer;
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Timer");
timeDisplay = new JLabel("...Waiting...");
resetButton = new JButton("Reset Timer");
this.add(resetButton);
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
event e = new event();
startButton.addActionListener(e);
event1 c = new event1();
stopButton.addActionListener(c);
event2 d = new event2();
resetButton.addActionListener(d);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Elapsed Time in Seconds: " + count);
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
public class TimeClass implements ActionListener{
int counter;
public TimeClass(int counter){
this.counter = counter;
}
public void actionPerformed(ActionEvent e){
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener{
public void actionPerformed (ActionEvent c){
timer.stop();
}
}
class event2 implements ActionListener{
public void actionPerformed (ActionEvent d){
timer.restart();
}
}
}
答案 0 :(得分:0)
在MyTimer
类
static volatile int counter;
....
class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
// handle the condition if start button is clicked
// more than once continuously.
if (timer == null) {
TimeClass tc = new TimeClass();
timer = new Timer(1000, tc);
}
timer.start();
}
}
class TimeClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener {
public void actionPerformed(ActionEvent c) {
// handle the condition if stop is clicked before starting the timer
if (timer != null) {
timer.stop();
}
}
}
class event2 implements ActionListener {
public void actionPerformed(ActionEvent d) {
// reset the counter
counter = 0;
// handle the condition if reset is clicked before starting the timer
if (timer != null) {
timer.restart();
}
}
}