GridBagLayout ipadY和定位

时间:2012-10-20 16:09:49

标签: java swing gridbaglayout

我有一个JFrame,它在窗口的左上角添加了一个窗格。这很好。出于某种原因,构成左上角窗格的gridbaglayout并不像我想要的那样。

我添加的前三个按钮位于第一个y行内并水平添加,但我添加到gridY = 1的informationPane不会转到下一行,它只是像按钮一样添加到右侧。

另外,我必须在每个按钮上使用设置首选大小,因为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

1 个答案:

答案 0 :(得分:2)

而不是

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

应该阅读

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

不应该吗?