I have a JPanel that should be positioned. I tried to use setBounds in the panels constructor, but it didn’t work. It seems like the bounds are forgotten when I call paintComponent.
public class Panel extends JPanel {
public Panel() {
setBounds(120,100,20,300);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Prints out (0,0)
System.out.println("Location: " + getLocation());
g.drawOval(0,0, 60, 60);
}
}
In Swing the positioning of a component is rarely determined by the component itself. It is usually determined by the LayoutManager of the container (which is affected, in turn, from its own container’s layout manager).
The rationale is that visual positioning is not a “divide and conquer” type of activity: The positioning of one component affects the positioning of the other components, so you need some sort of a “central positioning authority”, AKA: the layout manager.