且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Swing Timer更新标签

更新时间:2023-12-03 23:01:40

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

I don't really understand your question why you are using the Random, but here are some observations:


我想更新一个JLabel倒数,每秒。

I want to update a JLabel with the countdown, every second.

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

Then you need to set the Timer to fire every second. So the parameter to the Timer is 1000, not some random number.

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

Also, in your actionPerformed() method you stop the Timer the first time it fires. If you are doing a count down of some kind then you would only stop the Timer when the time reaches 0.

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

Here is a simple example of using a Timer. It just updates the time every second:

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 证明了这个问题。所有问题都应该有一个合适的SSCCE,而不仅仅是一些随机的代码行,这样我们才能理解代码的上下文。

If you need more help then update your question with a proper SSCCE demonstrating the problem. All questions should have a proper SSCCE, not just a few random lines of code so we can understand the context of the code.