繁体   English   中英

如何使用JLabel创建计时器?

[英]How can create timer with JLabel?

我想以这种方式在JPanel中显示带有计时器的JLabel,例如:

03:50 sec
03:49 sec
....
....
00:00 sec

所以我建立了这段代码:

@SuppressWarnings("serial")
class TimeRefreshRace extends JLabel implements Runnable {

    private boolean isAlive = false;

    public void start() {
        Thread t = new Thread(this);
        isAlive = true;
        t.start();
    }

    public void run() {
        int timeInSecond = 185
        int minutes = timeInSecond/60;
        while (isAlive) {
            try {
                //TODO
            } catch (InterruptedException e) {
                log.logStackTrace(e);
            }
        }
    }

}//fine autoclass

并使用此代码,我可以启动JLabel

TimeRefreshRace arLabel = new TimeRefreshRace ();
arLabel.start();

所以我有第二秒的时间,例如180秒,如何创建计时器?

您可以在try块中调用事件调度程序线程(EDT)并更新您的UI:

        try {
            SwingUtils.invokeLater(new Runnable() {
                @Override
                public void run() {
                    this.setText(minutes + " left");
                }
            }
            //You could optionally block your thread to update your label every second.
        }

(可选)您可以使用Timer而不是实际线程,因此TimerRefreshRace将具有自己的计时器,该计时器会定期触发事件。 然后,您将在try-catch块中使用相同的代码来更新UI。

这是一个示例,说明如何构建倒数标签。 您可以使用此模式来创建组件。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class TimerTest {

    public static void main(String[] args) {
        final JFrame frm = new JFrame("Countdown");
        final JLabel countdownLabel = new JLabel("03:00");
        final Timer t = new Timer(1000, new ActionListener() {
            int time = 180;
            @Override
            public void actionPerformed(ActionEvent e) {
                time--;
                countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
                if (time == 0) {
                    final Timer timer = (Timer) e.getSource();
                    timer.stop();
                }
            }
        });
        frm.add(countdownLabel);
        t.start();
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setVisible(true);
    }

    private static String format(int i) {
        String result = String.valueOf(i);
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM