Java中的Swing Timer秒表

时间:2015-11-02 21:22:02

标签: java swing timer stopwatch

有人可以使用不断更新的JLabel为我提供Java中Swing Timer秒表GUI的示例吗?我不熟悉使用@Override,所以除非绝对必要,否则请不要使用@Override建议代码(我已经完成了其他Swing Timers,例如系统时钟,没有它)。

谢谢!

编辑:根据@ VGR的请求,这里是我使用Swing Timer的基本时钟的代码:

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;

public class basic_clock extends JFrame
{
    JLabel date, time;

    public basic_clock()
    {
        super("clock");

        ActionListener listener = new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                Calendar current = Calendar.getInstance();
                current.setTime(new Date());
                date.setText((current.get(Calendar.MONTH) + 1) +"/" +current.get(Calendar.DATE) +"/" +current.get(Calendar.YEAR));
                String timeStr = String.format("%d:%02d:%02d", current.get(Calendar.HOUR), current.get(Calendar.MINUTE), current.get(Calendar.SECOND));
                time.setText(timeStr);                
            }
        };

        date = new JLabel();
        time = new JLabel();

        setLayout(new FlowLayout());
        setSize(310,190);
        setResizable(false);
        setVisible(true);

        add(date);
        add(time);

        date.setFont(new Font("Arial", Font.BOLD, 64));
        time.setFont(new Font("Arial", Font.BOLD, 64));

        javax.swing.Timer timer = new javax.swing.Timer(500, listener);
        timer.setInitialDelay(0);
        timer.start();
    }

    public static void main(String args[])
    {

        basic_clock c = new basic_clock();
        c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

显然我需要一些与Calendar对象不同的东西,因为我想跟踪最接近1/100秒的分钟和秒,而不是日期/月/年/小时/分钟/秒。

2 个答案:

答案 0 :(得分:2)

  

我为它做了谷歌,但我不理解我找到的代码

然后你有一个更大的问题。您如何期望我们中的任何一个人为您提供您可以理解的示例?

秒表在概念上非常简单,它只是自启动以来已经过去的时间量。当您希望能够暂停计时器时出现问题,因为您需要考虑计时器运行的时间加上自上次启动/恢复以来的时间。

另一个问题是,大多数计时器只能保证最短的时间,所以它们是不精确的。这意味着你不能只是将计时器的延迟量加到某个变量上,你最终会得到一个漂移的值(不准确)

这是一个非常简单的例子,它所提供的只是提供一个开始和停止按钮。每次启动秒表时,它都会再次从0开始。

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
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 SimpleStopWatch {

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

    public SimpleStopWatch() {
        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 StopWatchPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class StopWatchPane extends JPanel {

        private JLabel label;
        private long lastTickTime;
        private Timer timer;

        public StopWatchPane() {
            setLayout(new GridBagLayout());
            label = new JLabel(String.format("%04d:%02d:%02d.%03d", 0, 0, 0, 0));

            timer = new Timer(100, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long runningTime = System.currentTimeMillis() - lastTickTime;
                    Duration duration = Duration.ofMillis(runningTime);
                    long hours = duration.toHours();
                    duration = duration.minusHours(hours);
                    long minutes = duration.toMinutes();
                    duration = duration.minusMinutes(minutes);
                    long millis = duration.toMillis();
                    long seconds = millis / 1000;
                    millis -= (seconds * 1000);
                    label.setText(String.format("%04d:%02d:%02d.%03d", hours, minutes, seconds, millis));
                }
            });

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.insets = new Insets(4, 4, 4, 4);
            add(label, gbc);

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

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.weightx = 0;
            gbc.gridwidth = 1;
            add(start, gbc);
            gbc.gridx++;
            add(stop, gbc);
        }

    }

}

添加一个暂停功能并不难,只需要一个额外的变量,但我会把它留给你来解决。

答案 1 :(得分:1)

对于像我这样喜欢运动秒表的人来说,其想法是在单击开始按钮以及带有相应声音的“带上您的标记”按钮时发出声音。例如,在奥林匹克游泳比赛的录像带中,我录制了“加油打气”和发声时的哔哔声(练习时足以叫喊GO!)。使用MadProgrammer的答案,您将需要小的Jaco lib来播放所需的mp3文件。在Android应用程序中实现此功能是必经之路。

编辑:这本来应该是评论,但我对此仍然没有声望,因此,我想与大家分享这个想法,以区别于其他用途。

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
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;
import java.io.File;
import jaco.mp3.player.MP3Player;


public class TimerStopwatch {

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

    public TimerStopwatch() {
        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 StopWatchPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class StopWatchPane extends JPanel {

        private JLabel label;
        private long lastTickTime;
        private Timer timer;

        public StopWatchPane() {
            setLayout(new GridBagLayout());
            label = new JLabel(String.format("%02d:%02d:%02d.%03d", 0, 0, 0, 0));

            timer = new Timer(100, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long runningTime = System.currentTimeMillis() - lastTickTime;
                    Duration duration = Duration.ofMillis(runningTime);
                    long hours = duration.toHours();
                    duration = duration.minusHours(hours);
                    long minutes = duration.toMinutes();
                    duration = duration.minusMinutes(minutes);
                    long millis = duration.toMillis();
                    long seconds = millis / 1000;
                    millis -= (seconds * 1000);
                    label.setText(String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis));
                }
            });

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.insets = new Insets(4, 4, 4, 4);
            add(label, gbc);

            JButton start = new JButton("Start");
            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (!timer.isRunning()) {
                        lastTickTime = System.currentTimeMillis();
                        new MP3Player(new File("Beep.mp3")).play();
                        timer.start();


                    }
                }
            });
            JButton stop = new JButton("Stop");
            stop.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    timer.stop();
                }
            });

            JButton takeyourmarks = new JButton("Take your Marks");
            takeyourmarks.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new MP3Player(new File("Marks1.mp3")).play();
                }
            });

            JButton reset = new JButton("Reset");
            reset.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    label.setText(String.format("%02d:%02d:%02d.%03d", 0, 0, 0, 0));
                }
            });

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.weightx = 0;
            gbc.gridwidth = 1;
            add(takeyourmarks, gbc);
            gbc.gridx++;
            add(start, gbc);
            gbc.gridx++;
            add(stop, gbc);
            gbc.gridx++;
            add(reset, gbc);

        }

    }

}