【发布时间】:2014-12-08 12:00:34
【问题描述】:
我一直在尝试为我的程序实现一个计时器,但没有成功。我需要的是一个能够以秒计的计时器。我的想法是创建一个计时器,每秒将 1 添加到变量中,但我真的不知道该怎么做。计时器应在单击按钮 1 或按钮 2 时启动,并在单击按钮 3 时停止。顺便说一下,我必须使用 Swing 计时器,因为它涉及 GUI 程序。
如果有人能指出我正确的方向,那就太好了。我在 Java 中查找了计时器的语法,但我不明白(我是编码新手)。
这是代码(我省略了一些不重要的东西):
public class ColoredWordsExperiment {
JFrame frame;
JButton button1;
JButton button2;
JButton button3;
ButtonHandler buttonHandler;
Timer timer;
ColoredWordsExperiment(){
frame = new JFrame("Colored Words Experiment");
button1 = new JButton("Matching");
button2 = new JButton("Non-matching");
button3 = new JButton("Finished");
buttonHandler = new ButtonHandler(this);
button1.addActionListener(buttonHandler);
button2.addActionListener(buttonHandler);
button3.addActionListener(buttonHandler);
timer = new Timer(1000, buttonHandler);
}
public static void main(String[] arg) {
new ColoredWordsExperiment();
}
}
-
class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent e){
//If button "Matching" is clicked
if (e.getActionCommand().equals("Matching")) {
generateMatching();
timer();
//If button "Non-Matching is clicked
} else if (e.getActionCommand().equals("Non-matching")) {
generateNonMatching();
timer();
//If button "Finished" is clicked
} else if (e.getActionCommand().equals("Finished")) {
//stop timer
}
}
public void timer(){
coloredWords.timer.start();
}
}
【问题讨论】:
-
您会想先向我们展示您尝试解决这个问题的尝试,然后您会想问一个特定的问题或一组问题,告诉我们您遇到的确切位置以及具体是什么 i> 你不明白。否则你的问题会转化为我们,“请为我做我的工作”,我相信这不是你的意思。我会先查看 Swing Timers,包括在谷歌上搜索有关此的主要教程,并搜索此站点,因为这种事情经常被问到。
-
Google search -- 查看第一个命中。另外,请查看此StackOverflow search
-
为什么不捕获用户单击第一个按钮时的日期,然后捕获他们单击第二个按钮时的日期,然后从第二个日期中减去第一个日期以获得以秒为单位的差异。如果这是您想要的,则无需计时器。
-
@ Hovercraft Full Of Eels 我之前检查过那个链接和 stackoverflow 搜索,但我认为它们非常复杂,涉及“工人”和“线程”以及我仍然不知道的东西。不过谢谢你的建议。
-
BTW 计时器不会像您认为的那样做。它允许您安排在未来时间完成的任务。这不是秒表。