如何在JLabel上放置一个计时器来每秒更新一次

Mar*_*nos 4 java user-interface swing timer

我创建了一个游戏,在我的swing GUI界面中我想要一个计时器.我现在这样做的方式是有一个当前时间的字段,System.currentTimeMillis()当游戏开始时获得它的价值.在我的游戏方法中我放了 System.currentTimeMillis()- 字段; 它会告诉你自游戏开始以来的当前时间.

不过,如何JLabel让它每秒更新一次让我们说,所以会有:timePassed:0s,timePassed:1s等等.请记住,我在任何时候都不会在游戏中使用线程.

编辑:谢谢大家的善意建议.我用你的答案组合请给我一些反馈.

我将jlabel称为时间字段.(否则我无法处理它).

time = new JLabel("Time Passed:  " + timePassed() + " sec");
    panel_4.add(time);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            time.setText("Time Passed: " + timePassed() + " sec");
        }
    };
    Timer timer = new Timer(1000, actionListener);
    timer.start();
Run Code Online (Sandbox Code Playgroud)

小智 6

这就是我将JLabel设置为随时间和日期更新的方式.

Timer SimpleTimer = new Timer(1000, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        jLabel1.setText(SimpleDay.format(new Date()));
        jLabel2.setText(SimpleDate.format(new Date()));
        jLabel3.setText(SimpleTime.format(new Date()));
    }
});
SimpleTimer.start();
Run Code Online (Sandbox Code Playgroud)

然后将其添加到主类中,并使用计时器更新jlabel1/2/3.


How*_*ard 5

看看swing计时器课程.它允许非常容易地设置重复任务.