在Java中制作定时器



我能够在java中创建一个计时器,但我不能使用timer.stop()停止计时器。这是我的代码

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

这是有错误的部分,它说"变量'timer'可能尚未初始化"。我怎么做才能使程序识别定时器?

timer不能从匿名类(即监听器)中引用,使用((Timer)e.getSource()).stop();代替,或者,正如Hovercraft建议的那样,将逻辑封装到一个独立的类中,例如…

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Timer timer;
private int count = 300;
private JLabel label;
public TestPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JLabel label = new JLabel(Integer.toString(count));
label.setFont(new Font("Arial", Font.BOLD, 48));
label.setHorizontalAlignment(SwingConstants.CENTER);
add(label);
timer = new Timer(50, e -> {
count--;
if (count <= 0) {
timer.stop();
count = 0;
}
label.setText(String.valueOf(count));
});
timer.start();
}
}
}

最新更新