先请达人们告诉我发帖子的时候怎么以 JAVA Code的形式显示!
下面进入正题,我建了一个TestThreadInFrame窗口,里面有两个按钮,一个退出,另一个用来打开另一个窗口TimeWindow,然后在TimeWindow中想通过按钮触发事件:倒计时。利用线程的sleep来模拟计时,并且在TextField中显示数字,问题来了,倒计时貌似是在后台执行的,也就是说,textField中并没有实时更新,这是为什么呢?麻烦告诉下,救人如救火。。谢谢
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestThreadInFrame extends JFrame {
public static void main(String args[]){
TestThreadInFrame aaa=new TestThreadInFrame("name");
}
JButton timeButton,exitButton;
public TestThreadInFrame(String FrameName){
super(FrameName);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

timeButton=new JButton("Time");
exitButton=new JButton("Exit");
timeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){TimeWindow time=new TimeWindow();}
});
exitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){


System.exit(0);

}
});
setSize(400,200);
add(timeButton);
add(exitButton);
setVisible(true);
}

class TimeWindow extends JFrame{
JButton but=new JButton("time");
JLabel label=new JLabel("倒计时:");
JTextField textField=new JTextField(10);
public TimeWindow(){
super("WindowName");
setLayout(new FlowLayout());


textField.setEditable(false);
//Thread thread1=new Thread();
//thread1.start();

this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(200, 100);

add(but);
add(label);
add(textField);
this.setVisible(true);
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
this.callTimeWindow();
}
public void callTimeWindow(){

for(int i=5;i>=0;i--){

try{
Thread.currentThread().sleep(100);
}
catch (InterruptedException e){System.out.print("Exception");}
if(true) textField.setText(""+i);
}
}
});


}
}

}

解决方案 »

  1.   

    因为你点击按钮执行的callTimeWindow()方法占用了Swing本身的线程,使其根本没有时间去实时重绘textField。
    我把你的点击事件代码改了一下,放在另一个线程运行了:
      but.addActionListener(new   ActionListener(){
                    public   void   actionPerformed(ActionEvent   ae){
                       new Thread(){
                           public void run(){
                                callTimeWindow();                           
                           }
                       }.start();                   
                    }
                    public   void   callTimeWindow(){
                        for(int   i=5;i >=0;i--){
                            try{
                                Thread.currentThread().sleep(100);
                            } catch(InterruptedException  e){
                                System.out.print( "Exception ");
                            }
                            if(true)   textField.setText( " "+i);
                        }
                    }
                });
    另外推荐你看下这篇文章:http://www.javaresearch.org/article/10141.htm