java - 我如何等待 Java 计时器完成

标签 java multithreading swing timer

我有一个 java swing GUI,我试图在其中实现倒数计时器。我有一系列任务,每个任务都需要在 for 循环中按顺序运行。我已经能够成功地使用 Swing 计时器来执行倒数计时器,但是一旦我尝试将其放入循环中,我就无法在不卡住 GUI 的情况下更新它。

这是我目前工作的 SSCCE。基本问题是此示例并行运行三个 30 秒计时器。我想要做的是依次运行三个 30 秒计时器,或者换句话说,它应该等待一个计时器完成,然后再开始下一个计时器。我为尝试等待计时器完成所做的一切都会使 GUI 卡住。

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.security.auth.callback.Callback;
import javax.swing.*;

public class SwingTester extends JFrame {
  public SwingTester() {
    JPanel panel = new JPanel();
    getContentPane().add(panel);
    panel.setLayout(new GridLayout(1,3));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Add the components
    jLblTimer = new JLabel("00:30");
    jLblSet = new JLabel("Set #1");
    jBtnStart = new JButton("Start!");
    jBtnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {jBtnStartActionPerformed(evt);}
    });
    // Add the labels
    panel.add(jLblTimer); panel.add(jLblSet); panel.add(jBtnStart);
    pack();
  }
  private void jBtnStartActionPerformed(ActionEvent evt) {
    for (int ss=0; ss<3; ss++) {
        // Change the set name
        jLblSet.setText("Set #" + Integer.toString(ss+1));
        // Setup the counter to begin the countdown
        counter = 30;
        timer = new Timer(1000, startCycle());
        timer.start();
        // I want to wait here until the timer is done, nothing I've done
        // works without freezing the GUI.
    }
  }
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new SwingTester().setVisible(true);
      }
    });
  }
  private Action startCycle() {
    return new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new ClockTask(null).execute();
        }
    };
  }
  class ClockTask extends SwingWorker<Void, String> {
  private Callback callback;
  public ClockTask(Callback callback) {
    this.callback = callback;
  }
  @Override
  protected Void doInBackground() throws Exception {
    if (counter >= 0) {
      int millis = counter*1000;
      String time = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis),
        TimeUnit.MILLISECONDS.toSeconds(millis) -
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
        );
      publish(time); // call publish which will call process() method in EDT
      counter--;
    } else {
      // this.callback.call();
      this.callback.notify();
      timer.stop();
    }
    return(null);
  }
  @Override
  protected void process(List<String> times) {
    String lastTime = times.get(times.size()-1);
    jLblTimer.setText(lastTime); // just update ui with lastTimer, ohters are ignorable 
  }
  @Override
  protected void done() {
    super.done();
  }

  // private interface Callback {
  //   void call();
  // }
  }
  private javax.swing.JLabel jLblTimer;
  private javax.swing.JLabel jLblSet;
  private javax.swing.JButton jBtnStart;
  private javax.swing.Timer timer;
  private int counter;

}

我也尝试过使用 hibernate 功能等待倒计时结束,但这会阻止 GUI 更新。 欢迎提出任何建议。正如您可能从我的代码中看出的那样,我不是程序员。

最佳答案

下面是你需要如何改变你的 SwingWorker

class ClockTask extends SwingWorker<Void, String> {

    private Callback callback;

    public ClockTask(Callback callback) {
        this.callback = callback;
    }

    @Override
    protected Void doInBackground() throws Exception {
        if (counter >= 0) {
            int millis = counter*1000;
            String time = String.format("%02d:%02d", 
                TimeUnit.MILLISECONDS.toMinutes(millis),
                TimeUnit.MILLISECONDS.toSeconds(millis) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
            );

            //jLblTimer.setText(time); // dont update UI in backgroudn thread
            publish(time); // call publish which will call process() method in EDT

            counter--;
        } else {
            this.callback.call();
        }
        return(null);
    }

    /*
     * this  method will be called in EDT and will not freeze your UI ;)
     */
    @Override
    protected void process(List<String> times) {
        String lastTime = times.get(times.size()-1);
        jLblTimer.setText(lastTime); // just update ui with lastTimer, ohters are ignorable 
    }

    @Override
    protected void done() {
        super.done();
    }

    private interface Callback {
        void call();
    }

}

您应该多花一些时间在 SwingWorker 的 JavaDoc 上

关于java - 我如何等待 Java 计时器完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8454709/

相关文章:

java - 使用 JDBC 的多数据库连接(如 DB2、MySQL 等)的设计方法

c# - java.util.regex 的 C# 等价物是什么?

c++ - 有没有比下面更好的方法来使用C++并发?

c - 在 C++ 中并行化素数生成器

java - 如何在 JTabbedPane JComponent 面板中创建新行?

java - 多个 JPanel 完全重叠

java - 复制 joda LocalTime 的直接方法是什么?

java - 日本日期验证 - 比较

java - 无法在 Spring Boot 中的 Java 线程中 Autowiring beans

java - 在 JButton 上设置多个图标