我写了这个 Swing 计时器,它应该运行 10 次然后停止。但是,编译器表示 Timer
未初始化。我不想初始化它,也不需要初始化它( here 是一个未初始化但可以工作的示例)。怎么了?
public Enhanced() {
Timer picTimer ;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblTimer = new JLabel();
lblTimer.setBounds(361, 67, 61, 16);
contentPane.add(lblTimer);
ActionListener a = new ActionListener() {
int time=0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
if (++time > 10) {
picTimer.stop();
System.exit(0);
}
}
};
picTimer = new Timer(1000,a);
}
最佳答案
有一种方法可以避免引用外部计时器变量。
计时器实际上是您的 ActionListener
每次收到的事件的源。因此,您可以通过调用e.getSource()
来访问它。
这样,您甚至不需要提前声明计时器:
ActionListener a = new ActionListener() {
int time=0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
if (++time > 10) {
Timer timer = (Timer)e.getSource();
timer.stop();
System.exit(0);
}
}
};
new Timer(1000,a).start();
请注意,像这样调用 System.exit()
无论如何都会停止计时器。确实不建议这样调用System.exit()
。
关于java - N 次执行后停止 Swing 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618046/