简体   繁体   中英

Java Swing Use Date for Timer

Trying to make a timer that displays the time that has elapsed since a button has been pressed. I am using a Date instance and am trying to have it be initalized to 00:00:00 and have it increase by seconds, mins, then hours. it works as just a clock of the current time if I do not enter any values into Date currentTime = new date() Here is my code, I have tried setting the Date to all 0 values, and it displays as all zeros, but when my button is pressed, it no longer functions as a timer. What is the problem?

 Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Date currentTime = new Date(0,0,0,0,0,0);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                laserOnTimeTF.setText(sdf.format(currentTime));
            }
        });

        laserOnOff.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!laserSetting) {
                    timer.start();
                    laserSetting = true;
                    laserOnOff.setText("Laser On");
                } else {
                    timer.stop();
                    laserSetting = false;
                    laserOnOff.setText("Laser Off");
                }

            }
        });

That Date constructor is deprecated , like all Date constructors other than the one that takes a milliseconds argument. APIs are deprecated for a reason, usually because they don't work as intended. To be notified when you use deprecated APIs, turn on all compiler warnings in your IDE, and pay attention to those warnings.

Date is not a good fit for storing elapsed time, since it represents an absolute point in time. The class which is designed to represent a time difference is java.time.Duration .

You can calculate a Duration from two time values. The simplest time value is probably Instant , so you will want a private field of type Instant in the class which creates the Timer and adds a listener to the button, to keep track of when the button was pressed:

private Instant timeOfLastButtonPress;

Then you can initialize it each time the button is actually pressed:

laserOnOff.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (!laserSetting) {
            timeOfLastButtonPress = Instant.now();
            timer.start();
            laserSetting = true;
            laserOnOff.setText("Laser On");
        } else {
            timer.stop();
            laserSetting = false;
            laserOnOff.setText("Laser Off");
        }
    }
});

Finally, your Timer can calculate the Duration using Duration.between :

Duration elapsedTime =
    Duration.between(timeOfLastButtonPress, Instant.now());

If you're using Java 9 or later, you can extract the numbers from a Duration directly:

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Duration elapsedTime =
            Duration.between(timeOfLastButtonPress, Instant.now());
        laserOnTimeTF.setText(String.format("%02d:%02d:%02d",
            elapsedTime.toHoursPart(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart()));
    }
});

In Java 8, you will need to calculate it yourself:

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Duration elapsedTime =
            Duration.between(timeOfLastButtonPress, Instant.now());
        laserOnTimeTF.setText(String.format("%02d:%02d:%02d",
            elapsedTime.toHours(),
            elapsedTime.toMinutes() % 60,
            elapsedTime.getSeconds() % 60));
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM