我正在尝试在 Applet 中开发游戏,但遇到了这个问题。我希望在游戏继续之前显示屏向用户显示倒计时。但是,倒计时不会显示,实际上会使 GUI 卡住。如何避免这种情况?这是演示此问题的一些代码。
编辑:“几乎”下面的代码有效,计时器正在运行,但屏幕只会在按下“开始”按钮时更新为新的计时器值。如何让文字自动刷新?
public class TestApplet extends JApplet implements ActionListener{
final JTextField _displayField = new JTextField("Countdown", 6);
CountDownTimer clock = new CountDownTimer();
JButton jbtnStart = new JButton("Start");
public void addComponentToPane(Container pane) {
JPanel mainPanel = new JPanel();
mainPanel.add(jbtnStart);
mainPanel.add(_displayField);
pane.add(mainPanel);
jbtnStart.addActionListener(this);
}
public void init() {
TestApplet testApplet = new TestApplet();
testApplet.setVisible(true);
testApplet.addComponentToPane(this.getContentPane());
this.setSize(200, 100);
}
public void actionPerformed(ActionEvent e) {
if ( e.getSource() == jbtnStart ){
clock.start(_displayField);
}
}
}
// ********************************************************************************
//********************************************************************************
//********************************************************************************
class CountDownTimer {
private static final int N = 60;
private final ClockListener cl = new ClockListener();
private final Timer t = new Timer(1000, cl);
static int count =0;
public int getCount(){
System.out.println(count);
return count;
}
public void setCount(int n){
count = n;
}
public CountDownTimer() {
t.setInitialDelay(0);
}
public void start(JTextComponent c) {
t.start();
Boolean bool = false;
while ( bool ==false){
c.setText( "Starting new game in... "+ this.getCount() );
bool = ( this.getCount()<10 );
}
}
private class ClockListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
count %= N;
count++;
setCount(count);
}
}
}
最佳答案
ActionListener 中有一个 while 循环阻塞了 EDT。更新显示字段的代码不应位于 ActionListener 中。
相反,此代码应该位于 Timer 类中。然后,每当计时器触发时,您只需减去一并更新显示字段即可。当计数达到零时,您将停止计时器。
此外,您的 CountDownTimer 不应扩展 JFrame。它只是一个类,与框架无关。
编辑:
这是 Swing Timer 的简单用法:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class TimerTime extends JFrame implements ActionListener
{
JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
getContentPane().add(timeLabel, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e)
{
timeLabel.setText( new Date().toString() );
}
public static void main(String[] args)
{
TimerTime frame = new TimerTime();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
int time = 1000;
javax.swing.Timer timer = new javax.swing.Timer(time, frame);
timer.setInitialDelay(1);
timer.start();
}
}
关于java - 如何防止定时器锁定我的小程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836657/