有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带睡眠线程的java暂停秒表计时器?

我正在用Java制作秒表,但不知道如何暂停并继续计时。以下是我到目前为止所做的

startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);

public void actionPerformed(ActionEvent e) {
    Calendar aCalendar = Calendar.getInstance();
    if (e.getSource() == startButton){
        start = aCalendar.getTimeInMillis();
        startButton.setBackground(Color.GREEN);
        stopButton.setBackground(null);
        pauseButton.setBackground(null);
    } else if (e.getSource() == stopButton) {
        stopButton.setBackground(Color.RED);
        startButton.setBackground(null);
        pauseButton.setBackground(null);
        aJLabel.setText("Elapsed time is: " + 
                (double) (aCalendar.getTimeInMillis() - start) / 1000 );
    } else if (e.getSource() == pauseButton) {
        pauseButton.setBackground(Color.YELLOW);
        stopButton.setBackground(null);
        startButton.setBackground(null);
    }
}

如你所见,我只更改了暂停按钮的颜色。我真的不知道如何让用户点击按钮来暂停线程。我找到的所有关于线程的例子。sleep()是在特定的时间进行的


共 (1) 个答案

  1. # 1 楼答案

    你可以用秋千。计时器(不是util.Timer)如下所示:

    int interval = 100; // set milliseconds for each loop
    Timer timer = new Timer(interval, (evt) -> repeatingProccess());
    // create the method  repeatingProccess() with your
    // code that makes the clock tick
    
    
    startButton.addActionListener(e -> timer.start());
    stopButton.addActionListener( e -> {
        timer.stop(); 
        // here refresh your clock with some code... 
    };
    pauseButton.addActionListener(e -> timer.stop());
    

    您编写了一个名为repeatingProccess()的方法,它每隔interval毫秒在自己的线程中反复工作。对于计时秒的时钟,您可以执行以下操作:

    int interval = 1000;
    int seconds = 0;
    public void repeatingProccess() {
        seconds++ ;
    }
    

    注: 由于运行seconds++所需的时间,第二个时间不完全是1000毫秒,而是大约1001毫秒,但您也可以通过获取前后的系统时间并从时钟中减去差值来解决这一问题。为此,您应该使用日历API