这是github link
所以我试图创建一个应用程序并将其分解为3个部分,其中一个是创建一个计时器。此计时器有两个字段:一个输入分钟,一个输入秒。它应该用户输入几分钟或几秒钟,并在应用程序屏幕上显示倒计时。当计时器达到0时,它会提醒用户。我到处搜索,无法在Java中找到倒数计时器。我发现的所有倒计时器都可以在控制台或倒计时器中工作,这些计时器已经具有由开发人员设置的预定义值,而不是用户。
我想制作一个像谷歌这样的计时器: Google Timer
P.S。我是一名新的自学成才的程序员。这是我的第二个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();
}
}
更新 到目前为止,当用户设置小时并将分钟和秒留空时,它会从小时开始倒计时。与秒相同。但是,我无法得到相同的会议记录。如果我将所有内容留空除了分钟,计时器什么都不做。此外,我想让计时器与小时,分钟和秒同时工作。截至目前,它一次只能使用一个单元。
答案 0 :(得分:3)
所以,基本的想法是从Swing Timer
开始。使用它来更新UI是安全的,不会阻止UI线程并且可以定期重复。有关详细信息,请参阅How to use Swing Timers。
因为所有计时器只保证最小持续时间(也就是说,它们可以等待指定的延迟时间),所以不能仅仅通过添加预期的持续时间来更新状态值。相反,您需要能够计算时间点之间的时间差异。
为此,我将使用Java 8中引入的日期/时间API。有关详细信息,请参阅Period and Duration和Date and Time Classes。
从那里开始,设置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);
}
}
}
此计时器计时。我怎么能让它倒数呢?我尝试从你的链接中输入代码,但它不起作用。这些文件也没有帮助我理解太多。
这需要稍微更好地理解日期/时间API。
基本上,您需要知道预期的持续时间(计时器应运行多长时间)以及计时器运行的时间。由此,您可以计算剩余时间(倒计时)
为简单起见,我的开始是Duration
5分钟......
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
(就像我为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);
}
}
}