Java GUI repaint() problem?

Devoted picture Devoted · Dec 15, 2008 · Viewed 34.4k times · Source

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

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

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...

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Dec 15, 2008

Container.add API docs sayeth:

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.

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