JPanel forgets its position
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 paintCom开发者_JAVA技巧ponent(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.
In order to use absolute positioning (nothing I would recommend except in very rare cases) you have to remove the parents' layout manager by calling setLayout(null);
on the parent container:
getContentPane().setLayout(null);
getContentPane().add(new Panel());
精彩评论