0

I've searched everywhere for some simple code to print 60 seconds down, say on a JFrame constructor. So when a JFrame is run, the window title will be shown a countdown from 60-0 seconds (which in my case will shutdown). - No need for code to shutdown.

Something on the lines of:

JFrame frame = new JFrame("Window will terminate in: " + java.util.Calendar.SECOND);

Of course the code above does not make sense because it's printing the current time second. But you get the idea.

Douglas Grealis
  • 599
  • 2
  • 11
  • 25
  • searched everywhere? http://stackoverflow.com/questions/12908412/print-hello-world-every-x-seconds second result on google – alex Mar 14 '14 at 22:37
  • Yup I seen that one already, but that prints something every x seconds, it's different to what I'm looking for – Douglas Grealis Mar 14 '14 at 22:39
  • 1
    But you can easily adapt it for your needs. Send notification every one second and there you are! – alex Mar 14 '14 at 22:40

3 Answers3

4

Just create a Swing Timer and have a counter initialized at 60.

Set up the timer to be called every second.

Each time reduce the count by one and update the text.

When you reach 0 do whatever you do for the end of the countdown and stop the timer.

Tim B
  • 40,716
  • 16
  • 83
  • 128
3

Use a TimerTask to set the title of the JFrame every second.

public class TimerFrame {
    private static JFrame frame = new JFrame();

    public static void main(String[] args) {
        TimerFrame timerFrame = new TimerFrame();
        timerFrame.frame.setVisible(true);
        timerFrame.frame.setSize(400,100);
        new Timer().schedule(new TimerTask(){

            int second = 60;
            @Override
            public void run() {
                frame.setTitle("Application will close in " + second-- + " seconds.");
            }   
        },0, 1000);
    }
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks for your answer. Although I got this error when trying to compile the code: [code] error: constructor Timer in class Timer cannot be applied to given types; new Timer().schedule(new TimerTask(){ ^ required: int,ActionListener found: no arguments – Douglas Grealis Mar 14 '14 at 23:04
  • I am using JDK6 and it works fine. Did you copy the code or type it out? What JDK are you using? Make sure you are using `java.util.Timer` – Kevin Bowersox Mar 14 '14 at 23:14
2

Try this:

int count = 60;
while(count != 0){
        try {
            countlabel.setText(String.valueOf(count));
            count--;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Salah
  • 8,567
  • 3
  • 26
  • 43
  • Well, It's not a good practice to use `Thread.sleep` because it will freezes the frame until finishes, suppose the delay is `5` seconds, it'll freezes the frame for 5 seconds. Instead use `SwingTimer`, see `Tim B`'s answer. – Azad Mar 14 '14 at 23:02