如何将整数分割为字符串并自动以秒/分/小时为单位进行转换
我已经在GUI上设置并显示了一个计时器。如何将整数分割为字符串并自动以秒/分/小时为单位进行转换
我希望程序节省时间并加载它。我成功地做到了,但是, 我希望在程序启动时加载previou时间。
ms
是毫秒,所以如果它通过1000,它将它转换为1秒,并再次得到0的值。我创建了第二个(毫秒定时器)作为(分数)来显示,而不是将其更改为0.在计时器停止之前,分数不会自行重置。
我想抓住得分和与订单获取的值提取:
分钟/秒/毫秒。
我试图提取它或不同数量的划分,但它太困难对我说:/
简单地说,我想自动检测分的长度,并获得一个会议纪要,秒和毫秒字符串并在JLabel
后显示。
我可以创建其他整数为milliBackup
,secondsBackup
,minuteBackup
。 并分别将它们传递给毫秒/秒/分钟。但是,如果可以的话,我想这样做。
public void beginTimer() {
score++;
ms++;
if(ms==1000) {
ms = 0;
s++;
if(s>59) {
s = 0;
m++;
if(m>59) {
timer.cancel();
}
}
}
lblTimer.setText(displayTimer());
}
和DisplayTimer有:
public String displayTimer() {
return String.format("%02d:%02d:%03d", m, s, ms);
}
如何从score
计算分(m),秒(s)和毫秒(ms):
ms = score;
s = ms/1000; // integer div
ms = ms % 1000; // remainder
m = s/60; // integer div
s = s % 60; // remainder
你不说你是如何更新的方法。如果您打电话给Thread.sleep
,应该格外小心。有更好的方法。但是,使用您的代码:
// bad use of static but once you'll get it working, change it
static long s = 1;
static long m = 1;
static long ms = 1;
// the method is not beginTimer but updateTimer and goes inside a
// loop or something which calls it agan and again
public void updateTimer() {
if(ms==1000L) {
ms = 0;
s++;
if(s==60L) {
s = 0;
m++;
if(m==60L) {
timer.cancel();
}
}
}
lblTimer.setText(displayTimer());
}
我从util包使用定时器。这里是cod:timer = new Timer(); \t \t \t \t \t \t \t \t \t \t的TimerTask的TimerTask =新的TimerTask(){ \t \t \t \t \t \t @Override \t \t \t \t \t \t公共无效的run(){ \t \t \t \t \t \t \t \t \t \t \t \t \t \t beginTimer(); \t \t \t \t \t \t \t \t \t \t \t \t \t} \t \t \t \t \t \t \t \t \t \t \t}; \t \t \t \t \t \t \t \t \t \t timer.scheduleAtFixedRate(TimerTask的,1,1); – Erick
不错。请记住,'TimerTask'不保证实时执行。例如。不能确保它在确切的毫秒内更新计数器。但从长远来看,肯定会更新正确的**次数**。 –
嗯..运行最精确的计时器的最佳方式是什么? – Erick
这是更好地使用Java'日期时间API'。看看http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html – Nolequen