我在我的程序中遇到問題。我想在1秒內得到一個等於1000的實時毫秒。這是我的代碼:Java Swing.Timer獲得實時毫秒
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
class lsen implements ActionListener{
int ms = 0;
int s = 0;
int m = 0;
public void actionPerformed(ActionEvent e){
this.ms++;
if(this.ms == 500){
this.s++;
this.ms = 0;
}
if(this.s == 60){
this.m++;
this.s = 0;
}
}
public int getMS(){
return this.ms;
}
public int getSS(){
return this.s;
}
public int getMM(){
return this.m;
}
}
public class stopwatch_main{
public static void main(String[] args) {
lsen l = new lsen();
Timer t = new Timer(0,l);
t. start();
while(true){
System.out.println(l.getMM()+":"+l.getSS()+":"+l.getMS());
}
}
}
是否有任何其他方式獲得毫秒而不是聲明一個整數並遞增?
如果我正確理解了你,你的意圖是讓'actionPerformed'方法每秒被調用1000次,也就是每毫秒。這幾乎是不可能的。你可能會用自己的線程來接近它,並忙於等待*,但即使這樣也很難。 (這裏的「忙碌的等待」確實指的是一個無限制的while(true)循環 - 這與Java中最接近的「實時」相關,但你幾乎不必這樣做......) – Marco13 2014-08-31 14:27:06