问题是您的应用程序中只有一个线程.您应该至少有两个:一个用于更新文本的UI,另一个用于计算时间.
如果只有一个线程,它将挂在while(true)循环中,而Swing永远无法更新视图.
我使用两个线程重构了您的代码:
>一次计数直到时间结束,并更新字段以将时间保留在内存中
>每隔100毫秒调用一个使用java.util.Timer#scheduleAtFixedRate()方法的方法来更新视图.
Timer.java(避免像Java API中那样命名类)
public class Timer {
boolean shouldCount=false;
int int_sec=0;
int int_min=0;
int int_mil=0;
public Timer() {
}
public static void main(String[] args) {
TimeFrame t = new TimeFrame();
JFrame f = new JFrame("Timer");
f.setSize(300,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.getContentPane().add(new TimeFrame());
f.setVisible(true);
}
public void count(){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
while(true){
if(shouldCount){
if(System.currentTimeMillis()-now>=100){
now=System.currentTimeMillis();
int_mil++;
if(int_mil>9){
int_mil=0;
int_sec++;
if(int_sec>=60){
int_sec=1;
int_min++;
}
}
}
}
}
}
});
thread.start();
}
}
}
TimeFrame(我更喜欢将其称为TimePanel,因为它扩展了JPanel)
public class TimeFrame extends JPanel{
JLabel time;
Timer t ;
JButton pause ;
JButton start ;
public TimeFrame(){
t= new Timer(this);
time = new JLabel("Time goes here", JLabel.CENTER);
pause = new JButton ("Pause");
start = new JButton ("Start");
start.addActionListener(new starts());
pause.addActionListener(new starts());
add(time);
add(start);
add(pause);
java.util.Timer updateTimer= new java.util.Timer();
updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
t.update(int_sec,int_min,int_mil);
}
}, 0, 100);
}
public void update(int s, int minute,int m){
String sec = Integer.toString(s);
String min = Integer.toString(minute);
String mil = Integer.toString(m);
if (s<=10){
sec="0"+sec;
}
System.out.println(min+":"+sec+","+mil);
time.setText(min+":"+sec+","+mil);
}
public class starts implements ActionListener{
boolean firstTime=true;
public void actionPerformed(ActionEvent event){
if (firstTime){
t.count();
firstTime = false;
}
if(event.getSource() == start){
t.shouldCount=true;
}else{
t.shouldCount=false;
}
}
}
}