我想使用 swing 工作线程来更新 swing 中的 GUI。请提供任何帮助。我只需要使用线程即 setText() 更新 1 个字段的状态。
我刚刚在另一个论坛上回答了有关 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);
}
}
}
ps: @trashgod helps me a month ago to understand how to deal with SwingWorker (Can't get ArrayIndexOutOfBoundsException from Future<?> and SwingWorker if thread starts Executor https://stackoverflow.com/questions/7053865/cant-get-arrayindexoutofboundsexception-from-future-and-swingworker-if-thread/7054627#7054627), so thanks to him.
EDIT:代码已更正。谢谢 @装满鳗鱼的气垫船 https://stackoverflow.com/users/522444/hovercraft-full-of-eels
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)