在其他线程中更新界面

在事件分发线程中调用事件处理程序,如果该程序很耗时

,那么可能造成界面卡顿,举例如下:

public class JFrameBase extends JFrame
{
    public JFrameBase()
    {
        JButton btna = new JButton("耗时程序运行");
        btna.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                for(int i=0;i<1000000000;i++)
                {
                     System.out.println(i);
                }
            }
        });
        JButton btnb = new JButton("test");
        btnb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
               JOptionPane.showMessageDialog(null, "test");
            }
        });
        add(btna,BorderLayout.SOUTH);
        add(btnb,BorderLayout.NORTH);
        init();
    }
    public void init()
    {
        try
        {   
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {}
        this.setDefaultCloseOperation

(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setTitle("hello java swing");
        //this.setResizable(false);
        this.setVisible(true);
    }
    public static void main(String[] args)
    {
        new JFrameBase();
    }
}
1.png

点击下面的按钮后,上面的按钮不能点击了。如果添加一

个文本框,显示被3整除的数的个数,那么在其他线程中

更新界面,需要调用SwingUtilities.invokeLater方法,

把计算放到一个线程中,在线程计算完更新界面,调用

SwingUtilities.invokeLater进行更新。线程代码如下:

class ThreadTest extends Thread
{
    JTextField jtf;
    Runnable runable;
    int count = 0;
    public ThreadTest(JTextField jtf)
    {
        this.jtf = jtf;
        runable = new Runnable()
        {
            public void run()
            {
                jtf.setText("从0到1000000000之间被3整除的数为:"+count);
            }
        };
    }
    public void run()
    {
        for(int i=0;i<1000000000;i++)
        {
            if(i%3==0)
                count++;
        }
        SwingUtilities.invokeLater(runable );
    }

在按钮点击事件处理中创建线程并且启动。(new
ThreadTest(jtf)).start();
由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。