有时候需要将工作线程里的进度和结果更新显示到界面上。
原则:不要在工作线程里直接更新控件
原因:界面控件的方法一般是线程不安全的,在工作线程里操作界面一般是不安全的
解决办法:自己创建一个事件插到事件循环里面
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
MyFrame.textField.setText(progress);
}
});
在事件循环里,取出一个事件,发现是自定义事件处理,于是执行这个自定义事件的Runnable回调方法
code
package my;
import javax.swing.SwingUtilities;
public class ButtonThread extends Thread
{
@Override
public void run()
{
try
{
updateUI("我");
Thread.sleep(1000*2);
updateUI("爱");
Thread.sleep(1000*2);
updateUI("你");
Thread.sleep(1000*2);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//线程调度
private void updateUI(String progress)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run() {
MyFrame.textField.setText(progress);
}
});
}
}
package my;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyFrame extends JFrame
{
public static JTextField textField=new JTextField(10);
public static JButton button=new JButton("确定");
public MyFrame(String title)
{
super(title);
//面板
JPanel root=new JPanel();
this.setContentPane(root);
root.setLayout(new FlowLayout());
root.add(textField);
root.add(button);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
onButton();
}
});
}
private void onButton()
{
ButtonThread th=new ButtonThread();
th.start();
}
}
package my;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyDemo
{
private static void createGUI()
{
// JFrame指一个窗口,构造方法的参数为窗口标题
JFrame frame = new MyFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口的其他参数,如窗口大小
frame.setSize(500, 300);
// 显示窗口
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createGUI();
}
});
}
}