[英]how to put a timer on a JLabel to update itself every second
我创建了一个游戏,并在我的 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();
看看swing 定时器 class 。 它允许很容易地设置重复任务。
这就是我将 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();
然后将其添加到您的主 class 并且 jlabel1/2/3 将使用计时器进行更新。
new Thread(new Runnable
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
long time = System.currentTimeMillis() - start;
int seconds = time / 1000;
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
label.setText("Time Passed: " + seconds);
}
});
try { Thread.sleep(100); } catch(Exception e) {}
}
}
}).start();
在构造函数中写这个
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jMenu11.setText(CurrentTime());
}
};
Timer t = new Timer(1000, taskPerformer);
t.start();
而这个写出构造函数
公共字符串当前时间(){
Calendar cal = new GregorianCalendar();
int second = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR);
String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second));
jMenu11.setText(s);
return s;
}
public String checkTime(int t){
String time1;
if (t < 10){
time1 = ("0"+t);
}
else{
time1 = (""+t);
}
return time1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.