使用SwingWorker线程更新用户界面

4

我想使用Swing工作线程来更新Swing中的GUI。任何帮助都将不胜感激。我需要使用线程仅更新1个字段的状态,即setText()。

1个回答

8

我刚在另一个论坛上回答了关于SwingWorker的类似问题:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;


public class Main extends JFrame 
{
    private JLabel label;
    private Executor executor = Executors.newCachedThreadPool();
    private Timer timer;
    private int delay = 1000; // every 1 second

    public Main()
    {
        super("Number Generator");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 65);
        label = new JLabel("0");
        setLayout(new FlowLayout());
        getContentPane().add(label, "Center");
        prepareStartShedule();
        setVisible(true);
    }
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Main();
            }
        });
    }

    private void prepareStartShedule()
    {
        timer = new Timer(delay, startCycle());
        timer.start();
    }

    private Action startCycle()
    {
        return new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                executor.execute(new MyTask());
            }
        };
    }

    private class MyTask extends SwingWorker<Void, Integer>
    {
        @Override
        protected Void doInBackground() throws Exception
        {
            doTasksInBackground();
            return null;
        }

        private void doTasksInBackground()
        {
            publish(generateRandomNumber());
        }

        private int generateRandomNumber()
        {
            return (int) (Math.random() * 101);
        }

        @Override
        protected void process(List<Integer> chunks)
        {
            for(Integer chunk : chunks) label.setText("" + chunk);
        }

    }
}

:一个月前@trashgod帮助我理解如何处理SwingWorker(如果线程启动Executor,无法从Future<?>和SwingWorker获得ArrayIndexOutOfBoundsException),因此感谢他。


编辑:代码已经更正。感谢@Hovercraft Full Of Eels


如果do tasksInBackground需要一些时间(不是在这个例子中,但也许在真正的程序中),它应该在SwingWorker内完成,并且s应该通过publish(...)方法调用传递,然后通过process方法放入标签中。然后SwingWorker将更改为<Void,Integer>泛型类型。鉴于该方法的名称,我有99%的把握这样做是正确的。 - Hovercraft Full Of Eels
不错的更新,谢谢;也要感谢takteek。我对在这种情况下使用“Executor”很好奇,并找到了这篇有用的文章 - trashgod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接