UI update using swingworker thread

I want to use the swing workflow to update my GUI in swing. Any help pls appreciated. I need to update only the state of field 1 using the ie setText () stream.

+4
source share
1 answer

I just answer a similar question in another forum for a question about 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 figure out how to deal with SwingWorker ( Cannot get ArrayIndexOutOfBoundsException from the future <?> and SwingWorker if the thread launches Executor ), so thanks to him.


EDIT: Code fixed. Thanks @ Hovercraft Full Of Eels

+7
source

All Articles