【问题标题】:Revalidate and repaint - Java Swing重新验证和重新绘制 - Java Swing
【发布时间】:2012-12-09 16:34:05
【问题描述】:

我有一个要添加 JLabel 的 JPanel。然后我想删除所有的 JLabels 并添加一些新的。

所以我做了以下事情:

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

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

        panel.revalidate(); 

这很好用。当我在此之后开始一个新线程时出现了我的问题:

    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();
        }

那么原始 JLabels 的输出仍然可见。我已经读到重新验证过程是一个长时间运行的任务,因此 firstProducer 线程正在启​​动,而 重新验证正在进行中,并且发生了冲突。处理这个问题的最佳方法是什么?

【问题讨论】:

  • 1) “我有一个 JPanel,我正在向其中添加 JLabel。” 为什么?在 GUI 中使用带有文本 "" 的标签将使它们更易于使用,但不可见。 2) 确保长时间运行的操作不在 EDT 范围内,并且在其上进行 GUI 更新。为长时间运行的任务实现SwingWorker。有关详细信息,请参阅Concurrency in Swing

标签: java swing user-interface concurrency event-dispatching


【解决方案1】:

问题是firstProducer.join。如javadoc中所述

等待此线程终止。

因此,您将阻塞事件调度线程,直到您的另一个 Thread 完成,因此面板无法重新绘制或重新验证,您将不会在 UI 中看到您的更改。

更多信息请咨询Swing concurrency tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 2012-11-14
    • 2012-06-18
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    相关资源
    最近更新 更多