0

我需要制作一个 GUI,工人进入一个工作站(面板上的一个位置)并在那里停留一定时间,显示在工人头部的倒计时中(因此,一旦工人移动到该位置,工作站的标签显示 3s -> 2s -> 1s 然后工人离开,标签恢复为“OPEN”)。我在实现这一点时遇到了麻烦,因为我对 Java 的 Timer(s?) 不太了解。我尝试过这样的事情:

Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            //change label text/color, decrement countdown
            panel.repaint();
            Thread.sleep(1000);
        }
    });

但是我无法从计时器内部达到倒计时的秒数,而且我不确定如何将该值传递给计时器。如果有人可以帮助我,我将不胜感激。

4

2 回答 2

3

摆脱Thread.sleep(). 这就是1000inTimer(1000, new ActionListener()所做的。它为每个计时器事件设置一个间隔。每次触发计时器事件时,actionPerformed都会调用 。因此,您需要确定每个“滴答”需要发生什么,并将该代码放入actionPerformed. 也许像

Timer timer = new Timer(1000, new ActionListener() {
    private int count = 5;
    @Override
    public void actionPerformed(ActionEvent e) {
        if (count <= 0) {
            label.setText("OPEN");
            ((Timer)e.getSource()).stop();
            count = 5;
        } else {
            label.setText(Integer.toString(count);
            count--;
        }
    }
});

您需要决定何时调用timer.start()

于 2014-11-17T03:40:27.130 回答
1

问题 #1:您正在从 Swing GUI 线程中调用 Thread.sleep()。这会导致线程停止接受输入并冻结。删除该行。对你没有好处!当您使用它时,也请删除重绘调用。

既然已经说了又做了,那么您可以创建一个实现 ActionListener 并提供构造函数的实际类,而不是创建 ActionListener 的匿名实例。该构造函数可以将要开始倒计时的秒数作为参数。您可以在您正在使用的方法中声明该类,也可以在该类中声明它。

这是一个骨架示例:

public class OuterClass {
   JLabel secondsLabel = ...;
   Timer myTimer;

   private void setupTimer(int numSecondsToCountDown) {
      secondsLabel.setText(Integer.toString(numSecondsToCountDown));
      myTimer = new Timer(1000, new CountdownListener(numSecondsToCountDown));
      myTimer.start();
   }

   // ...
   class CountdownListener implements ActionListener {
      private int secondsCount;

      public CountdownListener(int startingSeconds) { secondsCount = startingSeconds; }

      public void actionPerformed(ActionEvent evt) {
         secondsLabel.setText(Integer.toString(secondsCount);
         secondsCount--;

         if (secondsCount <= 0) { // stop the countdown
            myTimer.stop();
         }
      }
   }
}
于 2014-11-17T04:06:17.567 回答