Domanda

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?

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top