2011-04-23 31 views
0

我有一个应该定位的JPanel。我试图在面板构造函数中使用setBounds,但它不起作用。当我调用paintComponent时,似乎忘记了边界。JPanel忘记其位置

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); 
    } 

} 

回答

3

在Swing组件的定位很少由组件本身决定。它通常由容器的LayoutManager确定(它受到自己容器的布局管理器的影响)。

其基本原理是视觉定位不是一种“分而治之”的活动类型:一个组件的定位影响其他组件的定位,因此您需要某种“中央定位权威”AKA:布局经理。

3

为了使用绝对定位(什么我会建议,除了在极少数情况下),必须在父容器上调用setLayout(null);除去父母的布局管理器:

getContentPane().setLayout(null); 
getContentPane().add(new Panel());