0

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

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

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

这是一张更清晰的图片,我希望绿色面板位于其他三个按钮下方:

在此处输入图像描述

4

1 回答 1

2

代替

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

它应该读

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

不应该吗??

于 2012-10-20T17:14:53.993 回答