如何在单击按钮时启动计时器?

时间:2014-10-13 20:15:10

标签: java timer

我一直在尝试为我的程序实现一个计时器而没有成功。我需要的是一个能够以秒计数的计时器。我的想法是创建一个每秒向变量添加1的计时器,但我真的不知道该怎么做。定时器应在单击button1或button2时启动,并在单击button3时停止。顺便说一下,我必须使用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();
}

}

1 个答案:

答案 0 :(得分:1)

你可以像这样创造自己的秒表:

public class Stopwatch { 

    private long start;

    public Stopwatch() {
        start = 0;
    } 

    public void start() {
        if(start == 0)
            start = System.currentTimeMillis();
    }

    // return time (in seconds) since this object was created
    public double elapsedTime() {
        if(start == 0) { return 0; } //You need to start it first

        long time = (System.currentTimeMillis() - start) / 1000.0;
        start = 0; // reset start to allow you to start it again later
        return time;
    }

然后只需创建一个秒表并在按下按钮1或2时启动它,并在按下按钮3时将其取回