Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GUI repaint() problem?

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

like image 711
Devoted Avatar asked Dec 15 '08 21:12

Devoted


People also ask

What is the difference between paint () and repaint () in swing?

The paint() method contains instructions for painting the specific component. The repaint() method, which can't be overridden, is more specific: it controls the update() to paint() process. You should call this method if you want a component to repaint itself or to change its look (but not the size).

Why can't you call paint () method directly instead of calling repaint () method?

Why cant we call paint (Graphics g) rather than repaint() ? Short answer: because then it would be called at the wrong time or possibly in the wrong thread (and without an appropriate Graphics). The Graphics object must be prepared and delivered by the JVM itself with help from the platform/operating system.

Why would a programmer use the repaint () method?

Whenever we want a component to repaint itself, we need to call the repaint method. In case we have made changes to the appearance of a component but have not made any changes to its size, then we can call the repaint method to update the new appearance of the component on the graphical user interface.

What does repaint () method does when it is called?

- The repaint() requests an erase and redraw (update) after a small time delay. - When you invoke repaint(), a message is sent to the native GUI requesting it to perform the action sometime in the distant future. - This method does not invoke paint() method directly.


1 Answers

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

like image 125
Tom Hawtin - tackline Avatar answered Nov 11 '22 19:11

Tom Hawtin - tackline