简体   繁体   中英

Revalidate and repaint - Java Swing

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM