我正在阅读有关该主题的不同线程,其中建议 Swing Timer class或SwingUtilities.InvokeLater
...但是我很难理解它们。
我使用atomicInteger来创建我的倒计时器,它在控制台中运行良好。但是,当我尝试将其合并到 Swing 中时,它仅更新开始值和结束值(例如,设置 5 秒倒计时将显示在框架中:“5”-> 5 秒后->“0”。
有什么简单的方法可以让我保留并“刷新”我的atomicInteger倒计时标签,或者唯一的方法是使用 Swing Timer 类?
感谢您的耐心等待!
ps。不是作业,只是想让自己成为一个定制的计时器来学习。 (即拖延)
我希望这个类足够了,如果您还需要框架/面板代码,请告诉我。
private class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
int t_study = 5;
atomicDown.set(t_study);
if (e.getSource() == b_study){
while(atomicDown.get() > 0){
t_study = atomicDown.decrementAndGet();
l_studyTime.setText(Integer.toString(t_study));
try {
Thread.sleep(1000);
}
catch (InterruptedException e1) {
System.out.println("ERROR: Thread.sleep()");
e1.printStackTrace();
}
}
}
else if(e.getSource() == b_exit){
System.exit(0);
}
else
System.out.println("ERROR: button troll");
}
}
最佳答案
将代码片段转换为 SSCCE 后,这就是我得到的(这似乎有效 - 尽我所能理解原始代码)。
我没有更改变量名称。请学习常用Java naming conventions 1 用于类、方法和属性名称并一致使用。
- 具体来说,像
b_study
这样的名称应该更类似于studyButton
或类似的名称。有些人会注意到“按钮”不应该是名称的一部分,但是当您有一个同时带有“学习”按钮和标签的 GUI 时,我看不到任何其他逻辑方法来分隔它们.
import java.awt.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.AtomicInteger;
class TimerTicker {
public static final int STUDY_TIME = 15;
AtomicInteger atomicDown = new AtomicInteger(STUDY_TIME);
JButton b_study;
JButton b_exit;
JLabel l_studyTime;
TimerTicker() {
JPanel gui = new JPanel();
b_study = new JButton("Study");
ClickListener listener = new ClickListener();
b_study.addActionListener(listener);
gui.add(b_study);
b_exit = new JButton("Exit");
b_exit.addActionListener(listener);
gui.add(b_exit);
l_studyTime = new JLabel("" + atomicDown.get());
gui.add(l_studyTime);
JOptionPane.showMessageDialog(null, gui);
}
private class ClickListener implements ActionListener {
Timer timer;
public void actionPerformed(ActionEvent e){
if (e.getSource() == b_study) {
ActionListener countDown = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (!(atomicDown.get() > 0)) {
timer.stop();
// reset the count.
atomicDown.set(STUDY_TIME);
} else {
l_studyTime.setText(
Integer.toString(
atomicDown.decrementAndGet()));
}
}
};
timer = new Timer(1000,countDown);
timer.start();
} else if(e.getSource() == b_exit) {
System.exit(0);
} else {
System.out.println("ERROR: button troll");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimerTicker();
}
});
}
}
关于Java:如何在ActionListener之后不断更新使用atomicInteger倒计时的JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10021969/