I am trying to develop a game in an Applet and I am having this problem. I would like the display to show a countdown to the user before the game continues. However, the countdown will not display and is actually making the GUI freeze up instead. How can this be avoided? Here is some code demonstrating this problem.
EDIT: Code below 'almost' works, timer is going but screen will only update to new timer value whenever Start button is pressed. How can I make the text refresh automatically?
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);
}
}
}