如何解决如何在JLabel上放置计时器以每秒更新一次
| 我创建了一个游戏,并且在我的摆动GUI界面中想放置一个计时器。我现在的方式是在当前时间创建一个字段,并用with0ѭ取,该值在游戏开始时得到它的值。在我的游戏方法中,我将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();
解决方法
看一下摆动计时器类。它可以很容易地设置重复任务。
, 这就是我将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();
然后将其添加到您的主类中,并使用计时器更新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();
这个写出来的构造函数
公共字符串CurrentTime(){
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。