我正在阅读有关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");
}
}
答案 0 :(得分:3)
将代码片段转换为SSCCE后,这就是我得到的(这似乎有效 - 就像我理解原始代码一样)。
我没有更改变量名称。请了解普通Java naming conventions 1 的课程,方法和方法。属性名称&一贯地使用它。
b_study
之类的名称应该更加符合studyButton
或类似名称。有些人会注意到'按钮'不应该是名称的一部分,但是当你有一个带有'研究'按钮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();
}
});
}
}