Chris
Chris

Reputation: 193

find how long swing timer has been running

I'm making a stop watch and I know how to do everything, except find how long my timer object has been going. Is there a method like timer.getElapsedTime() or something of that nature?

Edit: There are numbers saying 00 00 00. Every second it needs to increment. My thought process is seconds = timer.getElapsedTime(); secs.setText(seconds)

Upvotes: 2

Views: 2538

Answers (2)

Guntram Blohm
Guntram Blohm

Reputation: 9819

Just save System.currentTimeMillis() in some variable when you set your timer, and compare the value to the current return value when you need the elapsed time.

EDIT: Make the timer fire once every second. Note that we re-set the timer every time it fires to prevent lag and processing time from accumulating.

package timertest;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class TimerTest implements ActionListener {

    JLabel timeDisplay;
    long startTime;
    Timer timer;
    int seconds;

    public void createAndShowGUI()  {
        JFrame frame=new JFrame("Stopwatch");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        timeDisplay=new JLabel("0");
        frame.getContentPane().add(timeDisplay);
        frame.pack();
        frame.setVisible(true);

        startTime=System.currentTimeMillis();
        seconds=1;
        timer=new Timer(1000, this);
        timer.setRepeats(false);
        timer.start();
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TimerTest().createAndShowGUI();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        long now=System.currentTimeMillis();
        long elapsed=now-startTime;
        seconds++;
        timeDisplay.setText(elapsed+" Milliseconds since start");
        timer.setInitialDelay((int)(startTime+seconds*1000-now));
        timer.start();
    }
}

Upvotes: 1

Cruncher
Cruncher

Reputation: 7812

You can make your own timer class. (Or inherit from the current timer class and add this functionality)

public class Timer
{
    private long startTime = 0;

    public void start()
    {
        startTime = System.currentTimeMillis();
    }

    public int getElapsedTime() 
    {
        return (System.currentTimeMillis() - startTime) / 1000 //returns in seconds
    }
}

Upvotes: 1

Related Questions