I am trying to create a countdown timer using the javax.swing.Timer class.
In order to display it I am only allowed to use javax.swing.JFrame and javax.swing.TextField classes.
Well my Timer works as I expected. But I have trouble when I am trying to display it in the JFrame. It appears that nothing is added on the JFrame.
Here is my code:
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.event.*;
class CountdownTimer implements ActionListener {
final int TOTAL_TIME = 10;
int counter = TOTAL_TIME;
javax.swing.Timer refreshTimer;
//Creation of a JTextField
JTextField countdownTimerField ;
public CountdownTimer(JTextField f){
refreshTimer = new javax.swing.Timer(1000, this);
countdownTimerField = f;
}
public void actionPerformed(ActionEvent e) {
counter--;
if (counter >= 0){
//System.out.println(" ** " + counter);
countdownTimerField.setText(" ** " + counter);
}
if (counter == 0){
//System.out.println("Blast off! ");
countdownTimerField.setText(" Blast Off!");
stop();
}
}
public void start(){
refreshTimer.start();
}
public void stop(){
refreshTimer.stop();
}
public void reset(){
counter = TOTAL_TIME;
}
public static void main(String[] args)
{
JTextField timerField = new JTextField();
CountdownTimer cTimer = new CountdownTimer(timerField);
JFrame frame = new JFrame("Countdown Timer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(timerField);
frame.pack();
frame.setVisible(true);
}
}