Search code examples
javajframeseconds

Print 60 seconds countdown in Java


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.


Solution

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