我正在尝试在 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);
}
}
}