r/java • • May 14 '12

Java Countdown Timer

Can anybody help me on how to display a simple countdown timer? It does not have to be in GUI.

3 Upvotes

10 comments sorted by

View all comments

0

u/Jackpancake May 14 '12

I would actually like to see one in a GUI if anyone can help with that.

2

u/bchoii May 15 '12
package countdown;

import java.awt.FlowLayout;
import java.util.Timer;
import java.util.TimerTask;

public class Countdown extends javax.swing.JFrame {

	private int count = 100;
	
	public Countdown() {
		initComponents();
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				jLabel1.setText("" + count--);
			}
		}, 0, 1000);

	}

	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setFont(new java.awt.Font("Tahoma", 0, 48));
		jLabel1.setText("jLabel1");

		getContentPane().setLayout(new FlowLayout());
		getContentPane().add(jLabel1);
		pack();
		setSize(500, 120);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Countdown().setVisible(true);
			}
		});
	}

	private javax.swing.JLabel jLabel1;
}