2012-10-20 55 views
0

我有一個JFrame,在窗口的左上角添加一個窗格。這工作正常。出於某種原因,構成左上角窗格的gridbaglayout並不像我想要的那樣。GridBagLayout ipadY和定位

我添加的前三個按鈕位於第一個y行內部並且水平添加,但添加到gridY = 1的informationPane不會轉到下一行,它只會像按鈕一樣添加到右側。

另外,我不得不在每個按鈕上使用set preferred size,因爲iPadY並沒有垂直擴展按鈕。

private JPanel setUpTop() 
{ 
    JPanel pane = new JPanel(); 
    pane.setLayout(new GridLayout(1, 2)); 

    JPanel controlPane = new JPanel(); 
    pane.setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 


    controlPane.setBackground(Color.RED); 

    c.gridx = 0; 
    c.gridy = 0; 
    previousSongBT = new JButton("<<"); 
    previousSongBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT)); 
    controlPane.add(previousSongBT, c); 


    c.gridx = 1; 
    c.gridy = 0; 
    playBT = new JButton(">"); 
    playBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT)); 
    controlPane.add(playBT, c); 


    c.gridx = 2; 
    c.gridy = 0; 
    nextSongBT = new JButton(">>"); 
    nextSongBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT)); 
    controlPane.add(nextSongBT, c); 

    c.gridx = 0; 
    c.gridy = 1; 
    c.weighty = 1; 
    c.gridwidth = 3; 
    c.anchor = GridBagConstraints.PAGE_END; 
    JPanel informationPane = new JPanel(); 
    informationPane.add(new JButton("Bottom pane")); 
    informationPane.setBackground(Color.GREEN); 
    controlPane.add(informationPane, c); 

    pane.add(controlPane); 
    return pane; 
} 

下面是一個補充說,面板的代碼:

//Top-Left 
    c.anchor = GridBagConstraints.FIRST_LINE_START; 
    c.insets = new Insets(20,20,0,0); //top padding 

    c.gridx = 0; 
    c.gridy = 0; 
    c.weightx = 1; 
    c.weighty = 0.5; 
    this.getContentPane().add(setUpTop(), c); 

這裏有一個更清晰的圖片,我想綠色面板要低於其他三個按鈕:

enter image description here

+0

我不會用gridbag保持穩定,但是您是否嘗試將gridy設置爲更大的值? – cerealy

回答

2

而不是

JPanel controlPane = new JPanel(); 
pane.setLayout(new GridBagLayout()); 

它應該閱讀

JPanel controlPane = new JPanel(); 
controlPane.setLayout(new GridBagLayout()); 

不應該嗎?

+0

是的,不能相信我混合了這兩個JPanel的... ... –