Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The whole point of threads is that things are not executed in sequence. doInBackground() can finish (a while loop iteration) before process() is called. doInBackground() runs on the swing worker thread process() runs on the EDT.</p> <p>process() will run before done() (because it also runs on the EDT).</p> <p>As noted by the other answer: you should only publish the text, then create the JButton in process().</p> <p>Note normally you start a SwingWorker from the EDT, in that case you should not call get() on the EDT (which would block it).</p> <p>Simple example:</p> <pre><code>import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; public class SwingWorkerTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { final JPanel panel = new JPanel(new GridLayout(0, 1)); new SwingWorker&lt;Void, String&gt;() { @Override protected Void doInBackground() throws Exception { Random random = new Random(); int count = 1; while (count &lt; 100) { publish("Button " + (count++)); Thread.sleep(random.nextInt(1000) + 500); } return null; } @Override protected void process(List&lt;String&gt; chunks) { for (String text : chunks) { panel.add(new JButton(new AbstractAction(text) { @Override public void actionPerformed(ActionEvent e) { panel.remove((JButton) e.getSource()); panel.revalidate(); panel.repaint(); } })); } panel.revalidate(); panel.repaint(); } }.execute(); JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new JScrollPane(panel)); frame.setPreferredSize(new Dimension(400, 300)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload