2010-07-16 69 views
0

內容我有一個網格佈局面板(1,3),但我想集中細胞在此佈局的內容(不加面板):中心細胞網格佈局

public MainMenu() { 
     setLayout(new GridLayout(1, 3)); 

     setBorder(BorderFactory.createLineBorder(Color.BLUE)); 
     setOpaque(false); 


     ImageComponent img = new ImageComponent("resources/music.png", true, this); 
     add(img); 
     ImageComponent img1 = new ImageComponent("resources/video.png", true, this); 
     add(img1); 
     ImageComponent img2 = new ImageComponent("resources/audio", true, this); 
     add(img2); 


    } 

,因爲如果我只添加這3 ImageComponents到MainMenu它們向上出現。

回答

2

GridLayout將調整所有組件的大小以填充可用空間。因此,如果您的3個ImageComponents的尺寸是50x50,50x50和75x75,則它們的尺寸均爲75x75。從那裏它取決於ImageComponent如何繪製自己。

最有可能實現ImageComponent的paintComponent是這樣的:

protected void paintComponent(Graphics g) { 
    g.drawImage(image, 0, 0, this); 
} 

這將在左上角,不居中繪製圖像。

這將畫一個居中的圖像:

protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 
    int iw = image.getWidth(this); 
    int ih = image.getHeight(this); 

    if (iw != -1 && ih != -1) 
    { 
     int w = getWidth(); 
     int h = getHeight(); 
     g.drawImage(image, (w -iw)/2, (h-ih)/2, this); 
    } 
} 
+0

感謝德文!你是最棒的)))) – 2010-07-16 20:39:32

0

我相信你想要什麼,你需要調用你的圖像組件的setLayoutData - 檢查示例here