问题描述:Java Swing中,界面刷新是线程同步的,也就是说同一时间,只有一个线程能执行刷新界面的代码。如果要多次不断地刷新界面,必须在多线程中调用刷新的方法。
解决思路:
//主线程中的代码 当点击按钮时会执行 actionPerformed中的代码 。
在buttonActionPerformed方法中多次调用了setText方法来试图刷新JLabel。
buttonActionPerformed方法运行在主线程中,所以每次调用setText都是运行在主线程中,而且是顺序的执行的。在前面几次调用setText后,线程并没有退出,所以界面刷新线程不能获得执行刷新的机会。而当最后一次setText后,线程退出,界面才能执行刷新。所以我们只能看到最后一次setText的值。
因此,要解决这个问题,我们必须把buttonActionPerformed方法中的代码段放到一个单独的线程中执行。这样它就不会使线程阻塞,当每次setText后,界面刷新线程也能得到执行的机会,从而刷新界面。
// 相关主要代码如下
jb = new JButton("按钮");
jl = new JLabel("init", JLabel.CENTER);
jb.addActionListener(this);
this.add(jb, BorderLayout.NORTH);
this.add(jl, BorderLayout.CENTER);
this.setVisible(true);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setBounds(0, 0, 400, 400);
//
if (e.getActionCommand().equals("按钮")) { // TODO Auto-generated method stub
new Thread(new Runnable() {
public void run() { while(true){
System.out.println("please input the message");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr); String str="";
try { str = br.readLine();
} catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
jl.setText(str); } } }).start(); // 启动线程