4

I'm trying to implement a timer based scoring system for a puzzle application i am writing.

Can someone provide me with an example case of creating a JLabel or Panel in swing, containing a visibly counting timer (in seconds from 0), which stops, on a call from a method. And returns its value.

Example:

hrs:mins:seconds [00:00:00] [00:00:01] .. etc.. overwriting the previous entry.

Thanks

EDIT: this is an adaptation of the example code linked by trashgod: ClockExample, which uses simple if statements to display hours minutes and seconds...

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.Timer;

/** @see https://stackoverflow.com/questions/5528939*/
class ClockExample extends JFrame {

private static final int N = 60;
private static final String stop = "Stop";
private static final String start = "Start";
private final ClockListener cl = new ClockListener();
private final Timer t = new Timer(1000, cl);
private final JTextField tf = new JTextField(8);

public ClockExample() {
    t.setInitialDelay(0);

    JPanel panel = new JPanel();
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.setEditable(false);
    panel.add(tf);
    final JToggleButton b = new JToggleButton(stop);
    b.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (b.isSelected()) {
                t.stop();
                b.setText(start);
            } else {
                t.start();
                b.setText(stop);
            }
        }
    });
    panel.add(b);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.add(panel);
    this.setTitle("Timer");
    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

public void start() {
    t.start();
}

private class ClockListener implements ActionListener {

    private int hours;
    private int minutes;
    private int seconds;
    private String hour;
    private String minute;
    private String second;

    @Override
    public void actionPerformed(ActionEvent e) {
        NumberFormat formatter = new DecimalFormat("00");
        if (seconds == N) {
            seconds = 00;
            minutes++;
        }

        if (minutes == N) {
            minutes = 00;
            hours++;
        }
        hour = formatter.format(hours);
        minute = formatter.format(minutes);
        second = formatter.format(seconds);
        tf.setText(String.valueOf(hour + ":" + minute + ":" + second));
        seconds++;
    }
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            ClockExample clock = new ClockExample();
            clock.start();
        }
    });
  }
}

Thanks again all!

Community
  • 1
  • 1
Jay
  • 71
  • 1
  • 2
  • 7
  • 3
    I think you want to look into the swing Timer (http://download.oracle.com/javase/6/docs/api/index.html?javax/swing/Timer.html). It can be used to periodically fire an action until stopped. – Java Drinker Apr 21 '11 at 14:58
  • 1
    You might have a look at this [example](http://stackoverflow.com/questions/2163544/re-paint-problem-on-translucent-frame-panel-component/2166500#2166500). – trashgod Apr 21 '11 at 15:01
  • Here's another relevant [example](http://stackoverflow.com/questions/2704473/most-idiomatic-way-to-print-a-time-difference-in-java/2705674#2705674). – trashgod Apr 21 '11 at 15:19
  • 1
    @Jay: After checking out those examples, why not post your code attempt here and we can help you with it. – Hovercraft Full Of Eels Apr 21 '11 at 16:06
  • 1
    Okay! thanks for the examples ill take a look now! – Jay Apr 21 '11 at 16:36
  • 1
    @Jay: Excellent. That first example is a little abstruse; [this one](http://stackoverflow.com/questions/5528939/java-swing-two-classes-where-to-put-if-statements-and-new-actionlisteners/5529043#5529043) may a little clearer. – trashgod Apr 21 '11 at 17:14
  • 1
    @trashgod: AH that example is a little more useful! thanks for the link! With that example, i am currently trying to cause incrementation of minutes and hours as well as seconds. do you have any suggestions about going about this? thanks – Jay Apr 22 '11 at 07:59
  • 4
    @Jay: Well done! I think your use of `DecimalFormat` is a good choice. I would encourage you to move the example to an answer. – trashgod Apr 22 '11 at 08:47

1 Answers1

4

Thats a bit over-complicated. Instead of using seconds, minutes, hours, you could just use java.util.Date, and java.text.SimpleDateFormat for displaying the time passed.

start = new Date(); // time right now
sdf = new SimpleDateFormat("hh:mm:ss");

Then later to show what time has passed:

Date now = new Date();
sdf.format(new Date(now.getTime() - start.getTime()); //create a date based on time passed

This will have the same effect and be much clearer and more consise.

Adam L Davis
  • 269
  • 2
  • 5
  • 13