Search code examples
javaswingtimeractionlistenercountdown

How to display a Swing timer's remaining time in one second intervals?


I've been working on a simple game using a Java Applet in which the player's goal is to get as many points as possible within a 30 second timeframe. Right now, I'm using a Swing timer to count down from 30 seconds, and once the 0 mark is reached, a "game over" screen is displayed with the player's score. I have these instance variables:

ActionListener listener = new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
        screenState = 0;
        repaint();
    }
};

Timer displayTimer = new Timer(30000, listener);

When the player clicks the "play" button, I execute displayTimer.start();.

Then, I have this within the appropriate case in my paint class:

g.drawString("Time Remaining: " + displayTimer.getDelay()/1000, 650, 100);

So, obviously, right now it's just displaying a static "Time Remaining: 30", and the screens switches after 30 seconds. What I'm trying to figure out is how I can repaint this value every one second so that it's a live timer. The only help I've been able to find thus far is for people use components.


Solution

  • ActionListener listener = new ActionListener() {
    
         int count = 0;
    
         @Override
         public void actionPerformed(ActionEvent e) {
            if (count++==30) {
                screenState = 0;
            }
            repaint();
        }
    };
    
    Timer displayTimer = new Timer(1000, listener); // make it 30 times faster