如何在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称为时间字段。 (否则我无法处理它)。
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();
推荐答案
看一下 swing timer class 。它允许很容易地设置重复任务。
Have a look at the swing timer class. It allows to setup recurring tasks quite easily.
这篇关于如何在JLabel上放置一个计时器来每秒更新一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!