我的计时器gui面板出现问题



我正在制作一个计时器来配合我制作的数独网格,下面粗体的代码给了我错误,我不知道为什么。如果有人能指出任何错误并提供一个有帮助的解决方案。非常感谢。

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();**
            }
        }
    }
}

您将TimerClass变量用作内部类中的局部变量,但尚未将其声明为最终变量。您可以这样做,或者在类级别声明变量。

请注意,以后如果您对错误有疑问,请发布错误消息。


编辑
问题2:您已将此类命名为Timer!当您尝试使用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的本地变量。它应该是主程序的一个字段。

有关工作计时器的更好示例,请参阅此处的答案。

相关内容

  • 没有找到相关文章

最新更新