Java JPanel removeAll 不会删除以前的组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18001087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:40:26  来源:igfitidea点击:

JPanel removeAll doesn't get rid of previous components

javaswingjpanel

提问by jaybee

I have a swing application in which I display images in a JPanel. If the app is unable to produce the image I want to remove the previous one from the JPanel and replace it with a JTextField and message. I can add the text field , but it's drawn on top of the previous contents, which is itself a subclass of JPanel. Here's what I have:

我有一个 Swing 应用程序,在其中我在 JPanel 中显示图像。如果应用程序无法生成图像,我想从 JPanel 中删除前一个图像并将其替换为 JTextField 和消息。我可以添加 text field ,但是它是在前面的内容之上绘制的,它本身是 JPanel 的子类。这是我所拥有的:

private void displayMessage(String message) {
  JTextField tf = new JTextField(message);
  cdPanel.removeAll();
  cdPanel.add(tf, BorderLayout.NORTH);//tried lots of variations, inc. no layout    
  cdPanel.validate();
}

How can I get cdPanel to completely redraw itself?

我怎样才能让 cdPanel 完全重绘自己?

采纳答案by nIcE cOw

You can simply try calling :

您可以简单地尝试调用:

cdPanel.revalidate();
cdPanel.repaint();   // This is required in some cases

instead of

代替

cdPanel.validate();

回答by trashgod

As you are dealing with unpredictable latency, use a SwingWorkerto do the loading in the background, as shown here. The example uses pack()to resize the label to that of the image, but you may want to use a fixed-size grid and scale the images, as shown here.

当你在处理不可预测的延迟,用SwingWorker做负载的背景下,如图所示这里。例子中使用pack()的标签调整到的图像,但你可能需要使用一个固定大小的网格和缩放图像,如图所示这里