Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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.

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();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top