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);
    }
}

Recommended Answers

All 3 Replies

It would go a lot better if you started your Timer!

Please mark this "solved" so people know not to worry.
J

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.