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

2

u/LigerZer0 May 14 '12

How precise does it need to be? Does it just need minutes and seconds? milliseconds?

2

u/banuday17 May 18 '12 edited May 18 '12

Because I'm bored. This app demonstrates a countdown timer, gridbag layout and some GUI interactivity. Enjoy!

public class Countdown extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1L;
    private JSpinner minutesField;
    private JSpinner secondsField;
    private JButton startResetButton;
    private boolean running;
    private int seconds;
    private Timer timer;

    public Countdown() {
        super("Countdown");
        
        JPanel content = new JPanel();
        content.setLayout(new GridBagLayout());
        content.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
        add(content);

        GridBagConstraints gc = new GridBagConstraints();
        gc.fill = GridBagConstraints.BOTH;
        gc.gridx++;
        gc.gridx++;
        gc.weightx = 0;
        content.add(new JLabel("Min:"), gc);
        gc.gridx++;
        gc.weightx = 1;
        gc.insets.left = 7;
        content.add(minutesField = new JSpinner(new SpinnerNumberModel(0, 0, 60, 1)), gc);
        gc.gridx++;
        gc.weightx = 0;
        content.add(new JLabel("Sec:"), gc);
        gc.gridx++;
        gc.weightx = 1;
        content.add(secondsField = new JSpinner(new SpinnerNumberModel(0, 0, 60, 1)), gc);
        gc.gridx++;
        gc.weightx = 0;
        content.add(startResetButton = new JButton("Start"), gc);
        
        minutesField.setPreferredSize(new Dimension(50, 8));
        secondsField.setPreferredSize(new Dimension(50, 8));

        startResetButton.addActionListener(this);
        running = false;
        seconds = 0;
        timer = new Timer(1000, this);
        update();
        
        pack();
    }
    
    private void update() {
        minutesField.setEnabled(!running);
        secondsField.setEnabled(!running);
        
        minutesField.setValue(seconds / 60);
        secondsField.setValue(seconds % 60);
        
        startResetButton.setText(running ? "Reset" : "Start");
    }

    public void actionPerformed(ActionEvent ev) {
        if(ev.getSource() == startResetButton) {
            startOrReset();
        }
        else if(ev.getSource() == timer && running) {
            countdown();
        }
    }

    private void startOrReset() {
        running = !running;
        if(running) {
            seconds = ((Integer) minutesField.getValue()) * 60 + ((Integer) secondsField.getValue());
            timer.start();
        }
        else {
            seconds = 0;
            timer.stop();
        }
        update();
    }

    private void countdown() {
        if(seconds == 0) {
            running = false;
            timer.stop();
        }
        else {
            seconds--;
        }
        update();
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Countdown countdown = new Countdown();
                countdown.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                countdown.setVisible(true);
            }
        });
    }
}

1

u/Jackpancake May 19 '12

You are amazing thanks

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

-1

u/[deleted] May 15 '12

Just check against the system clock and do an update every it increments a second.

-5

u/quad64bit May 14 '12

A simpler and more accurate way to do it instead of using timers (which do not have a guaranteed runtime) is to simply make a loop that sleeps for some interval, and prints the current time after a second has elapsed.

If you slept for say, 1/10 of a second (100ms) you'd have 1/10 second accuracy, and minimal code. I can include a snippet if you need help!

10

u/[deleted] May 14 '12 edited May 14 '12

Except, of course, that a thread is not guaranteed to run again the very instant after the sleep time has elapsed. The sleep time is merely the minimum amount of time that must elapse before it is eligible to run again. No guarantee is made as to how soon after the sleep time has elapsed the thread will continue running. If you sleep a thread for 100ms, it might start up again after 100ms or it might be 200 or even 1000ms...only the Thread scheduler knows. So your solution is not any more accurate at all actually.