使用Swing Timer更新标签

我在使用这段代码时遇到了一些麻烦。

我正在用一个随机数启动一个计时器,我希望每秒都用倒计时更新一个JLabel。 但是我还没弄明白怎么做,因为定时器触发的唯一监听器就在它的末尾(我知道)。

这是代码:

int i = getTimer(maxWait); te1 = new Timer(i, this); label.setText(i+""); te1.start(); ... public int getTimer(int max){ Random generator = new Random(); int i = generator.nextInt(max); return i*1000; } ... public void actionPerformed(ActionEvent ev){ if(ev.getSource() == te1){ label.setText(i+""); te1.stop(); } } 

我真的不明白你的问题,为什么你使用Random,但这里有一些观察:

我想每秒钟倒计时更新一个JLabel。

然后你需要将Timer设置为每秒触发一次。 所以Timer的参数是1000,而不是一些随机数。

此外,在actionPerformed()方法中,第一次触发时会停止Timer。 如果您正在进行某种倒计时,那么只有在时间达到0时才会停止计时器。

这是一个使用Timer的简单示例。 它只是每秒更新一次:

 import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class TimerTime extends JPanel implements ActionListener { private JLabel timeLabel; public TimerTime() { timeLabel = new JLabel( new Date().toString() ); add( timeLabel ); Timer timer = new Timer(1000, this); timer.setInitialDelay(1); timer.start(); } @Override public void actionPerformed(ActionEvent e) { //System.out.println(e.getSource()); timeLabel.setText( new Date().toString() ); } private static void createAndShowUI() { JFrame frame = new JFrame("TimerTime"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add( new TimerTime() ); frame.setLocationByPlatform( true ); frame.pack(); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } 

如果您需要更多帮助,请使用适当的SSCCE更新您的问题,以certificate问题。 所有问题都应该有一个适当的SSCCE,而不仅仅是一些随机的代码行,这样我们就可以理解代码的上下文了。