Я делаю таймер, чтобы согласиться с сеткой sudoku im, и код, выделенный смелым, дает мне ошибки, и я не знаю, почему. Если кто-нибудь может указать на любые ошибки и предложить решение, которое было бы полезно. Спасибо.
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. Переименуйте свой класс в другое, скажем, 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();
}
}
}
У вас также есть проблемы с переменной count, поскольку она не может быть локальной для Timer ActionListener и Button. Это должно быть поле основной программы.
Для лучшего примера рабочего таймера, пожалуйста, см. Мой ответ здесь.