如何在 JLabel 上放置一个计时器以每秒更新一次 [英] how to put a timer on a JLabel to update itself every second
问题描述
我创建了一个游戏,我想在我的 Swing GUI 界面中放置一个计时器.我现在这样做的方法是有一个带有当前时间的字段,使用 System.currentTimeMillis()
获取它在游戏开始时获取它的值.在我的游戏方法中,我把 <代码>System.currentTimeMillis()- 字段;它会告诉您自游戏开始以来经过的当前时间.
I created a game and in my swing GUI interface I want to put a timer. The way I do this at the moment is have a field with the current time , gotten with System.currentTimeMillis()
which gets it's value when the game starts .In the method of my game i put the System.currentTimeMillis()
- field; and it tells you the current time passed since the game started.
尽管如此,如何让它每秒更新一次,让 JLabel
有: timePassed: 0s , timePassed: 1s 等等.请记住,我在任何时候都不会在游戏中使用线程.
Nevertheless, how do get this to update itself every second lets say, so the JLabel
will have : timePassed: 0s , timePassed: 1s and so on. Have in mind that i don't use threads in my game at any point.
谢谢大家的善意建议.我综合了你的回答,请给我一些反馈.
thank you all for your kind suggestions. I used a combination of your answers please give me some feedback.
我将 JLabel 作为名为 time 的字段.(否则我处理不了).
I have the JLabel as a field called time. (else i cant handle it).
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();
推荐答案
查看 摆动计时器类.它允许非常轻松地设置重复任务.
Have a look at the swing timer class. It allows to setup recurring tasks quite easily.
这篇关于如何在 JLabel 上放置一个计时器以每秒更新一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!