我正在制作一个计时器,以配合数独网格制作,粗体贝娄的代码给我错误,我不知道为什么。如果有人能够指出任何错误并提供一个有用的解决方案。谢谢。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Timer extends JPanel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
public Timer(){
final Timer timer;
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Button");
timeDisplay = new JLabel("...Waiting...");
resetButton = new JButton("Reset Timer");
this.add(resetButton);
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
class TimerClass implements ActionListener{
int counter;
public TimerClass(int counter){
this.counter = counter;
}
@Override
public void actionPerformed(ActionEvent tc) {
counter++;
}
}
class startButtonaction implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Time Elapsed in Seconds: " + count);
TimerClass tc = new TimerClass(count);
**timer = new Timer(1000, tc);
timer.start();**
}
}
}
}
答案 0 :(得分:2)
您正在使用TimerClass变量作为内部类中的局部变量,并且未将其声明为最终变量。你可以这样做,或者在类级别声明变量。
注意,将来如果您对错误有疑问,请发布错误消息。
修改强>
问题2:您已将此类命名为 计时器 !当您尝试使用Swing Timer时,这将导致名称冲突。将您的课程重命名为其他内容,例如 MyTimer 。
如,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends JPanel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
private Timer timer;
public MyTimer() {
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Button");
timeDisplay = new JLabel("...Waiting...");
resetButton = new JButton("Reset Timer");
this.add(resetButton);
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
}
private class TimerClass implements ActionListener {
int counter;
public TimerClass(int counter) {
this.counter = counter;
}
@Override
public void actionPerformed(ActionEvent tc) {
counter++;
}
}
private class startButtonaction implements ActionListener {
public void actionPerformed(ActionEvent e) {
int count = 0;
timeDisplay.setText("Time Elapsed in Seconds: " + count);
TimerClass tc = new TimerClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
}
您的计数变量也存在问题,因为它不能是Timer的ActionListener和Button的本地变量。它应该是主程序的一个领域。
有关工作计时器的更好示例,请参阅我的回答here。