简体   繁体   English

重新验证并重新绘制-Java Swing

[英]Revalidate and repaint - Java Swing

I have a JPanel that I am adding JLabel's to. 我有一个要添加JLabel的JPanel。 I then want to remove all the JLabels and add some new ones. 然后,我想删除所有的JLabel并添加一些新的JLabel。

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. 这样,原始JLabels的输出仍然可见。 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. 我已经读到,重新验证过程是一个长期运行的任务,因此在进行重新验证时会启动firstProducer线程,并且会发生冲突。 What is the best way to deal with this? 处理此问题的最佳方法是什么?

The problem is the firstProducer.join . 问题是firstProducer.join As stated in the javadoc 如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. 因此,您将阻止事件调度线程,直到其他Thread完成为止,因此无法重绘面板或重新验证面板,并且您将无法在UI中看到更改。

Consult the Swing concurrency tutorial for more information 有关更多信息,请查阅Swing并发教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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