I was able to make a timer in java, but I cant stop the timer with timer.stop() Here is my code
import javax.swing.*;
import java.awt.*;
public class Countdown {
public static void main(String[] args) {
JFrame frame = new JFrame("Countdown");
frame.setSize(300, 200);
JLabel label = new JLabel("300");
label.setFont(new Font("Arial", Font.BOLD, 48));
label.setHorizontalAlignment(SwingConstants.CENTER);
frame.add(label);
// Show the frame
frame.setVisible(true);
Timer timer = new Timer(1000, e -> {
int count = Integer.parseInt(label.getText());
count--;
label.setText(String.valueOf(count));
if (count == 0) {
timer.stop();
}
});
timer.start();
}
}
if (count == 0) {
timer.stop();
}
This is the part that has an error, it says "Variable 'timer' might not have been initialized". what can I do to make the program recognize the timer?