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
paintComponentis called from a few different places. The call fromJComponent.paintis probably the one you’re looking for.Note that
paintComponentis not called from any constructor. ThepaintComponentis 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.