I have a simple class that paints a graphic in a JPanel. This is my class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
class Drawing_panel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.white);
g.setColor(Color.red);
g.fillRect(150, 80, 20, 20);
}
public Dimension getPreferredSize(){
return new Dimension(500,500);
}
}
I have another class that instantiates this one:
Drawing_panel dp = new Drawing_panel();
There is no constructor in the Drawing_panel
class and/or no explicit call to either the paintComponent()
or getPreferredSize()
methods. I assume the method is being called in the parent JPanel
constructor, but I did not see the calls there either.
The paintComponent
is called from a few different places. The call from JComponent.paint
is probably the one you're looking for.
Note that paintComponent
is not called from any constructor. The paintComponent
is called "on-demand" i.e. when the system decides that the component needs to be redrawn. (Could for instance be when the component is resized, or when the window is restored from a minimized state.) To be clear: The component is not "painted, then used", it is "used, then painted when needed".
This whole chain of painting-calls is nothing you should bother about, as it is taken care of entirely by the Swing and the so called Event Dispatch Thread.
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