小编Yes*_*MPS的帖子

我是否在EDT之外更新Swing组件?

我一直在阅读很多关于Swing,线程,invokeLater(),SwingWorker等的内容,但我似乎无法理解这一切,所以我试图创建一个非常简单的程序来说明.我看了很多例子,但似乎没有一个例子表明我正在尝试做什么.

这是我在我的例子中想要做的事情.我有一个按钮和一个标签,当我单击按钮时,我希望程序暂停3秒钟,然后在标签文本中添加句点.在这3秒钟内,我希望GUI正常显示并继续响应额外的点击.这是我写的:

import javax.swing.SwingWorker;

public class NewJFrame extends javax.swing.JFrame
{
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;

    public NewJFrame()
    {
        initComponents();
    }
    private void initComponents()
    {
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setText("Button");
        jButton1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
        jLabel1.setText("Text");
        getContentPane().add(jLabel1, java.awt.BorderLayout.PAGE_END);
        pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
    {
        SwingWorker worker=new SwingWorker()
        {
            protected Object doInBackground()
            {
                try{Thread.sleep(3000);}
                catch (InterruptedException ex){}
                return null;
            }
        };
        worker.execute();
        jLabel1.setText(jLabel1.getText()+".");
    }

    public static void …
Run Code Online (Sandbox Code Playgroud)

java swing multithreading swingworker event-dispatch-thread

8
推荐指数
1
解决办法
554
查看次数