我正在阅读有关该主题的不同主题,其中建议摇摆定时器类 https://stackoverflow.com/questions/6811064/jlabel-displaying-countdown-java or SwingUtilities.InvokeLater https://stackoverflow.com/questions/2477155/how-to-update-jlabel-in-swing
......但我很难理解它们。
I used 原子整数创建我的倒计时器,它在控制台中运行良好。但是,当我尝试将其合并到 Swing 中时,它仅更新开始值和结束值(例如,设置 5 秒倒计时将显示在框架中:“5”-> 5 秒后->“0”。
有没有什么简单的方法适合我保留并“刷新”我的atomicInteger倒计时标签,或者唯一的方法是使用 Swing Timer 类?
感谢您的耐心等待!
附:不是作业,只是想让自己成为一个定制的计时器来学习。 (即拖延)
我希望这个类足够了,如果您还需要框架/面板代码,请告诉我。
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 后,这就是我得到的(这似乎有效 - 尽我所能理解原始代码)。
I have not changed the variable names. Please learn common Java naming conventions http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#733071 for class, method & attribute names & use it consistently.
- 具体名称如
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();
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)