[英]Displaying a timer in a panel using JLabel
So I am making a program with a fellow classmate and we haven't had much experience with GUI but what I am trying to do is display a timer of how long a user takes to complete a puzzle in a side panel (there's a main game area and a side panel beside it with buttons and such) but I'm not sure how I can get the JLabel
to constantly update with the time that the user takes to solve the puzzle. 因此,我正在与同班同学一起编写程序,我们在GUI方面没有太多经验,但是我想做的是在侧面板上显示用户完成拼图所需的时间的计时器(这是一个主要游戏区域以及旁边带有按钮等的侧面板),但我不确定如何使
JLabel
随用户解决难题所需的时间不断更新。 I don't know how I can use a timer object to do this so I've tried to use just System.nanoTime()
for now. 我不知道如何使用计时器对象来执行此操作,因此我现在尝试仅使用
System.nanoTime()
。
1) if I am using a timer object, what do I use in the Action listener parameters? 1)如果我使用计时器对象,该在Action侦听器参数中使用什么? Will this call the
timerLabel.updateUI();
这将调用
timerLabel.updateUI();
each time (assuming I have the actionPerformed method with that line of code in it already)? 每次(假设我已经有actionPerformed方法,其中已经包含那行代码)? Using a timer object what will I need to put into the Jlabel param when creating it?
使用计时器对象时,创建它时需要在Jlabel参数中放入什么?
2) if not using the timer object what would be the best way to update the time constantly? 2)如果不使用计时器对象,什么是不断更新时间的最佳方法?
//Timer timer = new Timer(1000, new ActionListener(??));
//timer.start();
long start = System.nanoTime();
String time = new java.text.SimpleDateFormat("ms").format(new java.util.Date(start/1000000));
timerlabel = new JLabel(time);
sideMenu.add(timerlabel);
timerlabel.updateUI();
You don't seem to understand how to use the ActionListener
. 您似乎不了解如何使用
ActionListener
。 ActionListener
doesn't take any parameters as it is an interface; ActionListener
不带任何参数,因为它是一个接口。 instead, you override its actionPerformed
method. 相反,您重写其
actionPerformed
方法。 What you might be looking for is this: 您可能正在寻找的是:
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
// Whatever action you want to happen every 1000 milliseconds
timerLabel.setText(new java.text.SimpleDateFormat("ms")
.format(new java.util.Date(System.nanoTime()/1000000)));
}
});
timer.start();
See here for more details or here for a pretty good example. 请参阅这里了解更多详情或在这里的一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.