0

I have a JPanel that I am adding JLabel's to. I then want to remove all the JLabels and add some new ones.

So I do the following:

        panel.removeAll();panel.repaint();

        panel.add(new JLabel("Add something new");

        panel.revalidate(); 

This works fine. My problem arises when I start a new thread after this like:

    panel.removeAll();panel.repaint();

    (1)panel.add(new JLabel("Add something new");

    panel.revalidate();

    //new thread to start - this thread creates new JLabels that should appear under (1)
    firstProducer.start();              

    try {

            firstProducer.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Then the output from the original JLabels is still visible. I have read that the revalidate process is a long running task and hence the firstProducer thread is getting started while the revalidation is going on and a conflict is arising. What is the best way to deal with this?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
M_x_r
  • 596
  • 4
  • 11
  • 26
  • 1
    1) *"I have a JPanel that I am adding JLabel's to."* Why? Having the labels in the GUI with text `""` will make them easier to use, but invisible. 2) Ensure long running operations are off the EDT, and GUI updates on it. Implement a `SwingWorker` for long running tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson Dec 09 '12 at 16:44

1 Answers1

4

The problem is the firstProducer.join. As stated in the javadoc

Waits for this thread to die.

So you are blocking the Event Dispatch Thread until your other Thread is finished, hence the panel cannot be repainted nor revalidated and you will not see your changes in the UI.

Consult the Swing concurrency tutorial for more information

Robin
  • 36,233
  • 5
  • 47
  • 99