JLabel 显示倒计时,java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6811064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:22:13  来源:igfitidea点击:

JLabel displaying countdown, java

javaswinguser-interfacejlabel

提问by Hurdler

I've got a "status" JLabel in one class (named Welcome) and the timer in another one (named Timer). Right now, the first one displays the word "status" and the second one should be doing the countdown. The way I would like it to be, but don't know how to - display 10, 9, 8, 7 ... 0 (and go to the next window then). My attempts so far:

我在一个班级(名为 Welcome)中有一个“状态”JLabel,在另一个班级(名为 Timer)中有一个计时器。现在,第一个显示“状态”一词,第二个应该进行倒计时。我想要的方式,但不知道如何 - 显示 10, 9, 8, 7 ... 0 (然后转到下一个窗口)。我到目前为止的尝试:

// class Welcome

setLayout(new BorderLayout());
JPanel area = new JPanel();
JLabel status = new JLabel("status");
area.setBackground(Color.darkGray);
Font font2 = new Font("SansSerif", Font.BOLD, 25);
status.setFont(font2);
status.setForeground(Color.green);      
area.add(status, BorderLayout.EAST); // can I put it in the bottom-right corner?
this.add(area);

and the timer:

和计时器:

 public class Timer implements Runnable {

//  public void runThread() {
//      new Thread(this).start();
//  }

public void setText(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            setText(text); // link to status here I guess
        }
    });
}

public void run() {
    for (int i = 10; i > 0; i--) {
        // set the label
        final String text = "(" + i + ") seconds left";
        setText(text);

//          // sleep for 1 second
//          try {
//              Thread.currentThread();
//              Thread.sleep(1000);
//          } catch (Exception ex) {
//          }
    }
    // go to the next window
    UsedBefore window2 = new UsedBefore();
    window2.setVisible(true);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // runThread();
}

} // end class

回答by Hovercraft Full Of Eels

I agree that you should consider using a "Java" Timer as per Anh Pham, but in actuality, there are several Timer classes available, and for your purposes a Swing Timer not a java.util.Timer as suggested by Anh would suit your purposes best.

我同意您应该考虑按照 Anh Pham 使用“Java”计时器,但实际上,有几个 Timer 类可用,出于您的目的,Swing Timer 而不是 Anh 建议的 java.util.Timer 适合您的目的最好的。

As for your problem, it's really nothing more than a simple problem of references. Give the class with the label a public method, say setCountDownLabelText(String text), and then call that method from the class that holds the timer. You'll need to have a reference of the GUI class with the timer JLabel in the other class.

至于你的问题,其实无非是简单的引用问题。为带有标签的类提供一个公共方法,例如setCountDownLabelText(String text),然后从持有计时器的类中调用该方法。您需要使用另一个类中的计时器 JLabel 引用 GUI 类。

For example:

例如:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Welcome extends JPanel {
   private static final String INTRO = "intro";
   private static final String USED_BEFORE = "used before";
   private CardLayout cardLayout = new CardLayout();
   private JLabel countDownLabel = new JLabel("", SwingConstants.CENTER);

   public Welcome() {
      JPanel introSouthPanel = new JPanel();
      introSouthPanel.add(new JLabel("Status:"));
      introSouthPanel.add(countDownLabel);

      JPanel introPanel = new JPanel();
      introPanel.setPreferredSize(new Dimension(400, 300));
      introPanel.setLayout(new BorderLayout());
      introPanel.add(new JLabel("WELCOME", SwingConstants.CENTER), BorderLayout.CENTER);
      introPanel.add(introSouthPanel, BorderLayout.SOUTH);

      JPanel usedBeforePanel = new JPanel(new BorderLayout());
      usedBeforePanel.setBackground(Color.pink);
      usedBeforePanel.add(new JLabel("Used Before", SwingConstants.CENTER));

      setLayout(cardLayout);
      add(introPanel, INTRO);
      add(usedBeforePanel, USED_BEFORE);

      new HurdlerTimer(this).start();
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("Welcome");
      frame.getContentPane().add(new Welcome());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }

   public void setCountDownLabelText(String text) {
      countDownLabel.setText(text);
   }

   public void showNextPanel() {
      cardLayout.next(this);
   }
}

class HurdlerTimer {
   private static final int TIMER_PERIOD = 1000;
   protected static final int MAX_COUNT = 10;
   private Welcome welcome; // holds a reference to the Welcome class
   private int count;

   public HurdlerTimer(Welcome welcome) {
      this.welcome = welcome; // initializes the reference to the Welcome class.
      String text = "(" + (MAX_COUNT - count) + ") seconds left";
      welcome.setCountDownLabelText(text);
   }

   public void start() {
      new Timer(TIMER_PERIOD, new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            if (count < MAX_COUNT) {
               count++;
               String text = "(" + (MAX_COUNT - count) + ") seconds left";
               welcome.setCountDownLabelText(text); // uses the reference to Welcome
            } else {
               ((Timer) e.getSource()).stop();
               welcome.showNextPanel();
            }
         }
      }).start();
   }

}

回答by Paul

Since you're using Swing you should use the javax.swing.Timer, not the java.util.Timer. You can set the timer to fire at 1 second (1000 ms) intervals and have your listener do the updating. Since Swing updates must take place in the event dispatch thread your listener is the perfect place for status.setText.

由于您使用的是 Swing,因此您应该使用javax.swing.Timer,而不是 java.util.Timer。您可以将计时器设置为以 1 秒(1000 毫秒)的间隔触发,并让您的听众进行更新。由于 Swing 更新必须在事件调度线程中进行,因此您的侦听器是status.setText.

回答by Anh Pham

回答by ben

Why not put the setText method in the welcome class and just do 'status.setText(text)'?

为什么不把 setText 方法放在欢迎类中,只做 'status.setText(text)'?

And you might try BorderLayout.SOUTH or .PAGE END or .LINE END to get the timer in the lower right corner

您可以尝试使用 BorderLayout.SOUTH 或 .PAGE END 或 .LINE END 来获取右下角的计时器