Java GUI 重绘()问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/369823/
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 13:55:14  来源:igfitidea点击:

Java GUI repaint() problem?

javauser-interfacerefreshjpanelrepaint

提问by Devoted

I have a JFrame. This JFrame contains a JButton. I click the JButton and 10 JTextFields are created.

我有一个 JFrame。这个 JFrame 包含一个 JButton。我单击 JButton 并创建了 10 个 JTextField。

the problem: I cannot see them until "I force a repaint()" by resizing the window. Only then do I see the JTextFields created.

问题:在“我通过调整窗口大小强制重绘()”之前我看不到它们。只有这样我才能看到创建的 JTextFields。

CODE:

代码:

JPanel points = new JPanel();

//Creating the JTextFields:
for (int i=0; i<10; i++) {
    JTextField textField = new JTextField();
    points.add(textField);
}

repaint();
this.repaint();
super.repaint();
points.repaint();


THANK YOU - after the for loop, I just called points.validate() and it worked...

谢谢 - 在 for 循环之后,我只是调用了 points.validate() 并且它起作用了......

采纳答案by Tom Hawtin - tackline

Container.addAPI docs sayeth:

Container.addAPI 文档说:

Note: If a component has been added to a container that has been displayed, validate must be called on that container to display the new component. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.

注意:如果组件已添加到已显示的容器中,则必须在该容器上调用 validate 以显示新组件。如果要添加多个组件,您可以在添加所有组件后仅调用一次 validate 来提高效率。

It's obscure and not very clever, but it's the rules. It may be better to call JComponent.revalidate

这很晦涩,也不是很聪明,但这是规则。打电话可能会更好JComponent.revalidate