繁体   English   中英

创建一个以用户输入开头的Java GUI倒数计时器

[英]create a java gui countdown timer that starts with user input

这是github 链接

因此,我试图创建一个应用程序并将其分解为3个部分,其中之一是创建一个计时器。 该计时器有两个字段:一个用于输入分钟,另一个用于输入秒。 用户应该在几分钟或几秒钟内输入,并在应用程序屏幕上显示倒计时。 当计时器达到0时,它将提醒用户。 我到处搜索,找不到Java中的倒数计时器。 我发现的都是在控制台中工作的倒数计时器或已经由开发人员而非用户设置的预定义值的倒数计时器。

我想制作一个与Google一样的计时器Google计时器

附言:我是一个新的自学成才的程序员。 这是我的第二个Java项目,所以我没有太多经验。 期待任何帮助:)

这是我的代码:

public class TestPane extends JFrame {

private LocalDateTime startTime;
private JLabel timerLabel;
private Timer timer;
private JButton startbtn;
private JTextField timeSet;
int count;
int count_2;
private Duration duration;
private JTextField minSet;
private JTextField secSet;


public TestPane() {


    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    setSize(400,400);
    getContentPane().setLayout(new CardLayout(0, 0));

    JPanel panel = new JPanel();
    getContentPane().add(panel, "name_87856346254020");
    panel.setLayout(null);

    timerLabel = new JLabel("New label");
    timerLabel.setBounds(59, 48, 194, 14);
    panel.add(timerLabel);

    startbtn = new JButton("New button");
    startbtn.setBounds(124, 187, 89, 23);
    panel.add(startbtn);

    timeSet = new JTextField(1);
    timeSet.setBounds(106, 85, 86, 20);
    panel.add(timeSet);
    timeSet.setColumns(10);

    JLabel lblHours = new JLabel("Hours");
    lblHours.setBounds(29, 88, 46, 14);
    panel.add(lblHours);

    JLabel lblMinss = new JLabel("Mins");
    lblMinss.setBounds(29, 114, 46, 14);
    panel.add(lblMinss);

    JLabel lblSecs = new JLabel("Secs");
    lblSecs.setBounds(29, 139, 46, 14);
    panel.add(lblSecs);

    minSet = new JTextField(60);
    minSet.setBounds(75, 116, 86, 20);
    panel.add(minSet);
    minSet.setColumns(10);

    secSet = new JTextField();
    secSet.setBounds(75, 147, 86, 20);
    panel.add(secSet);
    secSet.setColumns(10);


    startbtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                 startbtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timeSet.getText().trim();
                if(timeSet.getText().isEmpty()) {
                    duration = Duration.ofMinutes(count_min);
                } else {
                count_hour = Integer.parseInt(timeSet.getText());                   
                duration = Duration.ofHours(count_hour);                
                }

                minSet.getText().trim();                                
                if(minSet.getText().isEmpty()) {
                    duration = Duration.ofHours(count_hour);
                } else {
                    count_min = Integer.parseInt(minSet.getText());
                    duration = Duration.ofMinutes(count_min);                   
                }

                secSet.getText().trim();
                if(secSet.getText().isEmpty() && minSet.getText().isEmpty()) {
                duration = Duration.ofHours(count_hour);        
                } 
                else if(secSet.getText().isEmpty() && timeSet.getText().isEmpty()){
                    duration = Duration.ofMinutes(count_sec);
                }
                else {                  
                    count_sec = Integer.parseInt(secSet.getText());
                    duration = duration.ofSeconds(count_sec);
                }


                if (timer.isRunning()) {
                    timer.stop();
                    startTime = null;
                    startbtn.setText("Start");
                } 
                else {
                    startTime = LocalDateTime.now();
                    timer.start();
                    startbtn.setText("Stop");
                }

            }
        });           

        timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                LocalDateTime now = LocalDateTime.now();
                Duration runningTime = Duration.between(startTime, now);
                Duration timeLeft = duration.minus(runningTime);
                if (timeLeft.isZero() || timeLeft.isNegative()) {
                    timeLeft = Duration.ZERO;
                    startbtn.doClick(); // Cheat
                }

                timerLabel.setText(format(timeLeft));
            }
        });
    }

    protected String format(Duration duration) {
        long hours = duration.toHours();
        long mins = duration.minusHours(hours).toMinutes();
        long seconds = (duration.minusMinutes(mins).toMillis() / 1000) %60;
        return String.format("%02dh %02dm %02ds", hours, mins, seconds);
    }   


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

更新:到目前为止,当用户设置小时并将分钟和秒留为空白时,它从小时开始倒数。 与秒相同。 但是,我无法花几分钟来做同样的事情。 如果我将所有内容留空(分钟除外),则计时器不执行任何操作。 另外,我想使计时器与小时,分钟和秒同时工作。 截至目前,它一次只能使用一个装置。

在此处输入图片说明

因此,基本思想是从Swing Timer开始。 使用它来更新UI是安全的,不会阻塞UI线程,并且可以定期重复。 有关更多详细信息,请参见如何使用Swing计时器

由于所有计时器仅保证最短的持续时间(也就是说,它们可以等待的时间比指定的延迟时间更长),因此您不能仅通过添加期望的持续时间来依赖更新状态值。 相反,您需要能够计算时间点之间的时间差。

为此,我将使用Java 8中引入的Date / Time API。有关更多详细信息,请参见Period和Duration以及Date和Time类

从那里开始,只需设置一个Timer ,计算从开始时间到现在的Duration时间并格式化结果即可

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 java.time.LocalDateTime;
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 Test {

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

    public Test() {
        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 class TestPane extends JPanel {

        private LocalDateTime startTime;
        private JLabel label;
        private Timer timer;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            label = new JLabel("...");
            add(label, gbc);

            JButton btn = new JButton("Start");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                        startTime = null;
                        btn.setText("Start");
                    } else {
                        startTime = LocalDateTime.now();
                        timer.start();
                        btn.setText("Stop");
                    }
                }
            });
            add(btn, gbc);

            timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(startTime, now);
                    label.setText(format(duration));
                }
            });
        }

        protected String format(Duration duration) {
            long hours = duration.toHours();
            long mins = duration.minusHours(hours).toMinutes();
            long seconds = duration.minusMinutes(mins).toMillis() / 1000;
            return String.format("%02dh %02dm %02ds", hours, mins, seconds);
        }

    }


}

倒计时器...

此计时器开始计时。 我将如何倒数呢? 我尝试从您的链接中放入代码,但无法正常工作。 这些文档也没有帮助我了解太多。

这需要对Date / Time API有所了解。

基本上,您需要知道预期的持续时间(计时器应运行多长时间)以及计时器已运行的时间。 据此,您可以计算剩余时间(倒计时)

为简单起见,我以5分钟的Duration开始...

private Duration duration = Duration.ofMinutes(5);

每当Timer ,我只需计算运行时间并计算剩余时间...

LocalDateTime now = LocalDateTime.now();
Duration runningTime = Duration.between(startTime, now);
Duration timeLeft = duration.minus(runningTime);
if (timeLeft.isZero() || timeLeft.isNegative()) {
    timeLeft = Duration.ZERO;
    // Stop the timer and reset the UI
}

我真正所做的只是使用API​​。 我知道我最后需要一个Duration (因为这是我正在格式化的格式),所以我想保留它。 由于我还需要一个“持续时间”,以表示Timer应该运行的时间长度,因此Duration类似乎是一个不错的起点。

我原以为我可能需要计算差值between两个Duration S(像我一样的runningTime ),但事实证明,所有我真正想要的是(即从其他的一个减法),它们之间的区别。

剩下的就是添加检查以确保Timer不会出现负数时间,并且您知道“计时器”或“倒数”计时器的概念。

当您处理这些类型的问题时,从“可能”如何工作的“核心概念”入手始终是一件好事-即,从弄清楚您可能在几秒钟内倒计时开始。 这为您提供了一些基础工作,从那里您可以看到API提供了哪些支持以及如何利用它来发挥自己的优势。 在这种情况下, Duration非常简单,并且继续为输出的格式提供支持

例如...

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 java.time.LocalDateTime;
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 Test {

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

    public Test() {
        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 class TestPane extends JPanel {

        private LocalDateTime startTime;
        private JLabel label;
        private Timer timer;

        private Duration duration = Duration.ofMinutes(5);

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            label = new JLabel("...");
            add(label, gbc);

            JButton btn = new JButton("Start");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                        startTime = null;
                        btn.setText("Start");
                    } else {
                        startTime = LocalDateTime.now();
                        timer.start();
                        btn.setText("Stop");
                    }
                }
            });
            add(btn, gbc);

            timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    LocalDateTime now = LocalDateTime.now();
                    Duration runningTime = Duration.between(startTime, now);
                    Duration timeLeft = duration.minus(runningTime);
                    if (timeLeft.isZero() || timeLeft.isNegative()) {
                        timeLeft = Duration.ZERO;
                        btn.doClick(); // Cheat
                    }

                    label.setText(format(timeLeft));
                }
            });
        }

        protected String format(Duration duration) {
            long hours = duration.toHours();
            long mins = duration.minusHours(hours).toMinutes();
            long seconds = duration.minusMinutes(mins).toMillis() / 1000;
            return String.format("%02dh %02dm %02ds", hours, mins, seconds);
        }

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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