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...
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 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.
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.
- 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With