title: SwingWorker: creating Swing Components in worker thread and adding in EDT
body: <p>According to the <code>SwingWorker</code> Javadoc:</p>
  
  <blockquote>
    <p>When writing a multi-threaded application using Swing, there are two constraints to keep in mind:</p>
    
    <ul>
    <li>Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.</li>
    <li>Swing components should be accessed on the Event Dispatch Thread only.</li>
    </ul>
  </blockquote>
  
  <p>Thus, when using <code>SwingWorker</code>, we must access Swing Components only in <code>done()</code> and <code>process()</code> methods.</p>
  
  <p>So, I created a sample application which loads 3000 rows from database in chunks, each chunk with 50 rows and display it.</p>
  
  <pre><code>SwingWorker&lt;List&lt;Person&gt;, Person&gt; worker = 
     new SwingWorker&lt;List&lt;Person&gt;, Person&gt;() {
  
        protected List&lt;Person&gt; doInBackground() {
           List&lt;Person&gt; data = new ArrayList&lt;&gt;();
           while (hasMoreData()) {
              List&lt;Person&gt; chunk = loadFiftyRows();
              data.addAll(chunk);
              publish(chunk);
           }
           return data;
        }
  
        protected void process(List&lt;Person&gt; chunks) {
           for (Person person : chunks) {
              container.add(createPanelFor(person));
           }
           container.revalidate();
           container.repaint();
        }
  
     };
  worker.execute();
  </code></pre>
  
  <p>As, All swing access must be done on EDT, I am creating new <code>JPanel</code> instances for each <code>person</code> in the <code>process()</code> method. But, still the application is quite heavy on start up. It freezes and response to the events while the data is loading, is quite late.</p>
  
  <p>Although, we are publishing 50 rows at a time, the chunk size gets bigger when <code>process()</code> method is invoked on EDT, sometimes 1000 rows. I think this is the cause of the delay, creating 1000 instances of <code>JPanel</code> on EDT!</p>
  
  <p>I feel, creating 1000 new instances of <code>JPanel</code> is also a quite heavy task, to be performed on EDT. <strong>So, can't we create these <code>JPanel</code> instances in <code>doInBackground()</code> method, store it in a collection and then add those already created <code>JPanel</code> instances to the <code>container</code> in the <code>process</code> method?</strong></p>
  
  <p>But, it will contradict the statement, "Swing components should be accessed on the Event Dispatch Thread only"! </p>
  
  <p>Does this statement mean, <strong>Existing Swing Components that have been added to the Swing Component Hierarchy and not newly created Swing Components?</strong></p>