BoxLayout如何实现组件从上到下排列,从左到右堆叠?

6
我有一个使用 BoxLayoutX_AXIS 方向上的 JPanel。最好通过一张图片来说明我的问题: alt text 如您所见,左侧的 JPanel 已居中而不是顶部对齐。我希望它们都在顶部对齐,并从左到右堆叠。使用这个布局管理器该怎么做?我编写的代码如下:
public GameSelectionPanel(){

    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

    setAlignmentY(TOP_ALIGNMENT);

    setBorder(BorderFactory.createLineBorder(Color.black));

    JPanel botSelectionPanel = new JPanel();

    botSelectionPanel.setLayout(new BoxLayout(botSelectionPanel, BoxLayout.Y_AXIS));

    botSelectionPanel.setBorder(BorderFactory.createLineBorder(Color.red));

    JLabel command = new JLabel("Please select your opponent:"); 

    ButtonGroup group = new ButtonGroup();

    JRadioButton button1 = new JRadioButton("hello world");
    JRadioButton button2 = new JRadioButton("hello world");
    JRadioButton button3 = new JRadioButton("hello world");
    JRadioButton button4 = new JRadioButton("hello world");

    group.add(button1);
    group.add(button2);
    group.add(button3);
    group.add(button4);

    botSelectionPanel.add(command);
    botSelectionPanel.add(button1);
    botSelectionPanel.add(button2);
    botSelectionPanel.add(button3);
    botSelectionPanel.add(button4);

    JPanel blindSelectionPanel = new JPanel();
    blindSelectionPanel.setBorder(BorderFactory.createLineBorder(Color.yellow));

    blindSelectionPanel.setLayout(new BoxLayout(blindSelectionPanel, BoxLayout.Y_AXIS));

    JRadioButton button5 = new JRadioButton("hello world");
    JRadioButton button6 = new JRadioButton("hello world");

    ButtonGroup group2 = new ButtonGroup();
    group2.add(button5);
    group2.add(button6);

    JLabel blindStructureQuestion = new JLabel("Please select the blind structure:");

    blindSelectionPanel.add(blindStructureQuestion);
    blindSelectionPanel.add(button5);
    blindSelectionPanel.add(button6);

    add(botSelectionPanel);
    add(blindSelectionPanel);

    setVisible(true);
}
2个回答

5

Riduidel关于在GameSelectionPanel本身上设置setAlignmentY是正确的,而GridBagLayout是一个很好的替代方案。如果您更喜欢使用BoxLayout,文章解决对齐问题讨论了这个问题,建议“所有由从左到右的BoxLayout控制的组件通常应具有相同的Y对齐方式。” 在您的示例中,添加

botSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
blindSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);

2

嗯,setAlignmentY方法在这里没有效果,因为它作用于被视为组件的面板。

正如您所猜测的那样,包含面板的布局由您使用的布局管理器定义。 不幸的是,BoxLayout不能提供您正在寻找的功能。

在标准JDK中,显然您问题的首选布局是GridBagLayout。虽然一开始很难理解,但它将快速展示出其在组件排列方面的强大能力。

使用有用的GBC类,您的组件可以排列如下:

setLayout(new GridBagLayout(this));

add(botSelectionPanel, new GBC(0,1).setAnchor(TOP));
add(blindSelectionPanel, new GBC(0,2).setAnchor(TOP));

或者我认为是这样;-)

哇,伙计,关于那个GBC类的链接很棒。虽然我开始使用GridBagConstraints的全构造函数,但我学会了参数位置。但对于小的GUI来说,使用GBC是一个不错的选择。对于较大的GUI,我认为一行完整的GridBagConstraints构造函数是最好的解决方案。 - Timmos
GridBagLayout的构造函数没有输入参数。 - Stepan Yakovenko
您的示例引发了异常:在线程“AWT-EventQueue-0”中,java.lang.IllegalArgumentException:非法的锚点值。 - Stepan Yakovenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接