[英]How to split an integer into String and Convert it automatically by seconds/minutes/hours
I have set and displayed a timer on GUI.我已经在 GUI 上设置并显示了一个计时器。
I want the program to Save the time and load it.我希望程序节省时间并加载它。 I did it successfully but, I Want whenever the program start, to load the previou time.
我成功了,但是,我想在程序启动时加载以前的时间。
ms
is Milliseconds that every so if it passes 1000 it converts it to 1 seconds and get's the value of 0 again. ms
是毫秒,所以如果它通过 1000 它将它转换为 1 秒并再次获得 0 的值。 I Have created a second (millisecondTimer) as (score) to display and not change it to 0. The score doesn't reset's itself until the timer stops.我创建了一个秒 (millisecondTimer) 作为 (score) 来显示而不是将其更改为 0。在计时器停止之前,分数不会重置自身。
I Want to grab the score and extract in with an order to get the values of:我想获取分数并按顺序提取以获得以下值:
Minutes / Seconds / Milliseconds .分/秒/毫秒。
I Have tried to extract it or divide it by different numbers but it's too difficult to me :/我试图提取它或将其除以不同的数字,但对我来说太难了:/
Simply, I want to automatically detect the length of a score and get the Minutes, seconds and milliseconds on a String and display it after on JLabel
.简单地说,我想自动检测分数的长度并在 String 上获取分钟、秒和毫秒,然后在
JLabel
上显示它。
I could create other integers as milliBackup
, secondsBackup
, minuteBackup
.我可以创建其他整数作为
milliBackup
, secondsBackup
, minuteBackup
。 and pass them separately to miliseconds/seconds/minutes.并将它们分别传递到毫秒/秒/分钟。 But I want to do it in this way if it is able.
但如果可以的话,我想这样做。
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());
}
and DisplayTimer has:和 DisplayTimer 有:
public String displayTimer() {
return String.format("%02d:%02d:%03d", m, s, ms);
}
You don't say how you're updating the method.你没有说你如何更新方法。 If you're calling
Thread.sleep
, extra care should be used.如果您正在调用
Thread.sleep
,则应格外小心。 There are better methods.有更好的方法。 But using your code:
但是使用您的代码:
// 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());
}
How to calculate minutes (m), seconds (s), and milliseconds (ms) from score
:如何从
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.