[英]How to split an integer into String and Convert it automatically by seconds/minutes/hours
我已经在 GUI 上设置并显示了一个计时器。
我希望程序节省时间并加载它。 我成功了,但是,我想在程序启动时加载以前的时间。
ms
是毫秒,所以如果它通过 1000 它将它转换为 1 秒并再次获得 0 的值。 我创建了一个秒 (millisecondTimer) 作为 (score) 来显示而不是将其更改为 0。在计时器停止之前,分数不会重置自身。
我想获取分数并按顺序提取以获得以下值:
分/秒/毫秒。
我试图提取它或将其除以不同的数字,但对我来说太难了:/
简单地说,我想自动检测分数的长度并在 String 上获取分钟、秒和毫秒,然后在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);
}
你没有说你如何更新方法。 如果您正在调用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());
}
如何从score
计算分钟 (m)、秒 (s) 和毫秒 (ms):
ms = score;
s = ms / 1000; // integer div
ms = ms % 1000; // remainder
m = s / 60; // integer div
s = s % 60; // remainder
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.