简体   繁体   English

在按开始按钮到特定时间(HH:mm:ss)格式后,如何设置初始延迟

[英]How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format

I need to set a specific time in JTextfield format (HH:mm:ss). 我需要以JTextfield格式(HH:mm:ss)设置特定时间。 And I need to set the initialDelay which will be the time after I pressed the button "Start" and time specified in JTextField. 而且我需要设置initialDelay ,它是按下按钮“开始”后的时间和在JTextField中指定的时间。 After the time is passed, it will be opened a new JFrame . 时间过去之后,将打开一个新的JFrame

I have tied to parse the String into date (HH:mm:ss) and calculate the difference between specified time and local time. 我必须将String解析为日期(HH:mm:ss)并计算指定时间与本地时间之间的时差。

 private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
       if(evt.getActionCommand().equals("Start")){

          if(onTime.isSelected()){

                  String time1= onTimeTextfiled.getText();
                  LocalTime localTime = LocalTime.parse(time1, DateTimeFormatter.ofPattern("HH:mm:ss"));

                  LocalTime loc = LocalTime.now();
                  if(localTime.compareTo(loc)==0){
                        frame2.setSize(600,800);
                        frame2.setVisible(true);

                  }

          }

Using a JTextField to parse a date format doesn't sound great because the risk of a parse exception will be high. 使用JTextField解析日期格式听起来并不好,因为解析异常的风险很高。 I suggest you to use another component(s), or try to find some external date/time pickers. 我建议您使用其他组件,或尝试查找一些外部日期/时间选择器。 However, nothing stops you from using java.time API in order to parse the date, calculate the delay and create the timer. 但是,没有什么可以阻止您使用java.time API来解析日期,计算延迟和创建计时器。

I have created an example: 我创建了一个示例:

public class Example extends JFrame {
    private static final long serialVersionUID = 1L;
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    private Timer timer;

    public Example() {
        super("test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        JTextField field = new JTextField(10);
        add(field);

        JButton startTimer = new JButton("Start");
        startTimer.addActionListener(e -> {
            try {
                LocalTime selectedTime = LocalTime.parse(field.getText(), formatter);
                LocalDateTime selectedDate = LocalDateTime.now().toLocalDate().atStartOfDay();
                selectedDate = selectedDate.plusHours(selectedTime.getHour()).plusMinutes(selectedTime.getMinute())
                        .plusSeconds(selectedTime.getSecond());
                // Check if time has passed and should be scheduled for tomorrow
                if (selectedDate.isBefore(LocalDateTime.now())) {
                    selectedDate = selectedDate.plusDays(1);
                }
                long date = Timestamp.valueOf(selectedDate).getTime();
                long delay = date - System.currentTimeMillis();
                timer = new Timer((int) delay, e1 -> {
                    JOptionPane.showMessageDialog(null, "Time passed.");
                });
                timer.setRepeats(false);
                timer.start();
                System.out.println("Timer started and scheduled at: " + selectedDate);
            } catch (DateTimeParseException e1) {
                JOptionPane.showMessageDialog(null, "Cannot parse date.");
                System.out.println(e1);
            }
        });
        add(startTimer);

        setSize(300, 300);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new Example().setVisible(true);
        });
    }
}

Using JSpinner s for time input is simple enough and makes the implementation more robust. 使用JSpinner进行时间输入非常简单,并使实现更可靠。
The following example is a one-file MRE (copy and paste the entire code into SwingTest.java and run): 以下示例是一个文件的MRE(将整个代码复制并粘贴到SwingTest.java并运行):

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;

public class SwingTest extends JFrame {

    public SwingTest()  {
        getContentPane().add(new MainPanel());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        pack();
        setVisible(true);
    }

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

class MainPanel extends JPanel{

    private final Timer timer;

    MainPanel() {
        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        setLayout(new BorderLayout(10,10));
        TimePanel tp = new TimePanel();
        add(tp);
        JButton btn = new JButton("Open a window at selected time");
        btn.addActionListener(e -> processTime(tp.getTime()));
        add(btn, BorderLayout.PAGE_END);
        timer = new Timer(0, e->openNewWindow());
        timer.setRepeats(false);
    }

    private void processTime(LocalTime time) {

        if(time == null || timer.isRunning()) return;
        LocalTime now = LocalTime.now();

        long delayInSeconds = ChronoUnit.SECONDS.between(now, time);

        if (delayInSeconds < 0) {   //if time is before now
            delayInSeconds += 1440; //add 24X60 seconds
        }

        System.out.println("opening a window in "+ delayInSeconds + " seconds");
        timer.setInitialDelay((int) (delayInSeconds * 1000));
        timer.start();
    }

    private void openNewWindow() {
        timer.stop();
        JOptionPane.showMessageDialog(this, "New Window Opened !");
    }
}

class TimePanel extends JPanel {

    JSpinner hours, minutes, secconds;

    TimePanel() {

        hours = new JSpinner(new SpinnerNumberModel(12, 0, 24, 01));
        minutes = new JSpinner(new SpinnerNumberModel(0, 0, 60, 01));
        secconds = new JSpinner(new SpinnerNumberModel(0, 0, 60, 01));

        setLayout(new GridLayout(1, 3, 10, 10));
        add(hours);
        add(minutes);
        add(secconds);
    }

    LocalTime getTime(){

        String h = String.valueOf(hours.getValue());
        String m = String.valueOf(minutes.getValue());
        String s = String.valueOf(secconds.getValue());
       StringBuilder time = new StringBuilder();
       time.append(h.length() < 2 ? 0+h: h).append(":")
           .append(m.length() < 2 ? 0+m: m).append(":")
           .append(s.length() < 2 ? 0+s: s);
       System.out.println(time.toString());
       return LocalTime.parse(time.toString(), DateTimeFormatter.ofPattern("HH:mm:ss"));
    }
}

在此处输入图片说明

暂无
暂无

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

相关问题 如何将毫秒之间的两个时间之间的时差直接转换为hh:mm:ss格式? - How can I directly convert the difference between two time in milliseconds to a hh:mm:ss format? 如何将给定格式的时间设置为零yyyy-MM-dd HH:mm:ss(Java) - How set the time to zero in given format yyyy-MM-dd HH:mm:ss(Java) 如何格式化时间以出现在FormattedJTextField中的格式为hh:mm,但之后没有AM或PM? - How can I format a time to appear in a FormattedJTextField in the format hh:mm, with no AM or PM after it? 经过时间格式HH:mm:ss - Elapsed time format HH:mm:ss 如何将时间戳从yyyy-MM-ddThh:mm:ss:SSSZ格式转换为MM / dd / yyyy hh:mm:ss.SSS格式?从ISO8601到UTC - How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC 如何将日期和时间格式从“ yyyy-MM-dd HH:mm:ss”更改为“ h:mm a”? - How to change date and time format from“yyyy-MM-dd HH:mm:ss” to “h:mm a”? 如何将毫秒转换为“hh:mm:ss”格式? - How to convert milliseconds to "hh:mm:ss" format? 如何以“ HH:mm:ss”格式添加秒表? - How to add stopwatch in “HH:mm:ss” format? 如何以这种格式“HH:mm:ss”转换秒 - How to convert the seconds in this format "HH:mm:ss" 如何使用 Selenium 根据表格中显示的上传时间验证字符串 HH:MM:SS - How can I validate a String HH:MM:SS against the upload time displayed in a table using Selenium
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM