2011-04-23 56 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());