Java - updating existing stopwatch code to include countdown

和自甴很熟 提交于 2019-12-02 07:55:51

This makes use of the new Java 8 Time API to simplify the process, allowing your to calculate durations between two points in time as well as arithmetic

See Date and Time Classes

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalTime;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class StopWatch {

    public static void main(String[] args) {
        new StopWatch();
    }

    public StopWatch() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final String TIME_FORMAT = "%02dh %02dm %02ds";

        private LocalTime startTime;
        private LocalTime targetTime;

        private JLabel label;
        private JButton start;

        private Timer timer;

        public TestPane() {
            label = new JLabel(formatDuration(Duration.ofMillis(0)));

            start = new JButton("Start");
            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();

                        Duration runningTime = Duration.between(startTime, LocalTime.now());
                        // Subtract the required amount of time from the duration
                        runningTime = runningTime.minusSeconds(5);

                        // No negative times
                        if (runningTime.toMillis() > 0) {
                            // When the timer is to end...
                            targetTime = LocalTime.now().plus(runningTime);
                            timer.start();
                        }
                    } else {
                        startTime = LocalTime.now();
                        timer.start();
                    }
                }
            });

            timer = new Timer(500, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (targetTime != null) {
                        Duration duration = Duration.between(LocalTime.now(), targetTime);
                        if (duration.toMillis() <= 0) {
                            duration = Duration.ofMillis(0);
                            timer.stop();
                            targetTime = null;
                        }
                        label.setText(formatDuration(duration));
                    } else {
                        // Count up...
                        Duration duration = Duration.between(startTime, LocalTime.now());
                        label.setText(formatDuration(duration));
                    }
                }
            });

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(label, gbc);
            add(start, gbc);

        }

        protected String formatDuration(Duration duration) {
            long hours = duration.toHours();
            duration = duration.minusHours(hours);
            long mins = duration.toMinutes();
            duration = duration.minusMinutes(mins);
            long seconds = duration.toMillis() / 1000;

            return String.format(TIME_FORMAT, hours, mins, seconds);
        }

    }

}

I also want to remove the "Pause" and "Stop" buttons (you would think they would be easy to remove, but I removed what I thought was appropriate and received an error when compiling) and replace them with the single "Submit" button.

Take a look at Creating a GUI With JFC/Swing for more details

Unfortunately I don't understand the majority of Hovercraft's code

And any other solution we provide you will have the same result. You need to break down you requirements into manageable chunks, work out how the timer moves forward, then work out how you can make it move backwards, then work out how you can combine the two concepts so you can subtract a target value from the running time and move it backwards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!