Jakob991 Jakob991 - 1 year ago 123
Java Question

Creating a Countdown Timer inside of a JFrame

I have been struggling on this problem for a while so I thought I'd seek out some help.

I am creating an application for a game which requires me to make a dynamic countdown timer. By dynamic I mean being able to put your desired countdown timer in as the consumer. The problem I'm having is making my code wait 1000 milliseconds to execute the update code with the correct time. I am attempting to use the

functionality to do this...

This is not the application I am making this is just to simplify my problem down as much as I could for anyone willing to help me. Everything in here is directly from WindowBuilder in Eclipse IDE. The issue I'm having is getting the
Thread thread = new Thread();
work with
for the full 1 second delay.

package test;

import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import java.awt.Font;

public class test {

private JFrame frame;

* Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
} catch (Exception e) {

* Create the application.
public test() {

* Initialize the contents of the frame.

private void initialize() {
frame = new JFrame();

JLabel lblNewLabel = new JLabel("Test");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 62));
frame.getContentPane().add(lblNewLabel, BorderLayout.CENTER);
frame.setBounds(100, 100, 450, 300);

Thread thread = new Thread();

for(int i = 60;i>=0;i--){
lblNewLabel.setText("Test" + i);



If you throw this code in your IDE an error that reads
Unhandled exception InterruptedException
comes up. If I add in throws declarations the code just messes all up truthfully I don't know what the problem is there.

How can I fix or work around this?

Answer Source

Here's another way to do it. Please note this code is not test.

private void initialize() {
    new Thread() {
        int counter = 10;
        public void run() {
            while(counter >= 0) {
                lblNewLabel.setText("Test" + (counter--));
                } catch(Exception e) {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download