6

我有一个JPanel使用 aBoxLayoutX_AXIS方向。我遇到的问题最好用一张图片来说明: 替代文字

如您所见,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);
}
4

2 回答 2

5

RiduidelsetAlignmentY对自身的设置是正确的GameSelectionPanelGridBagLayout是一个很好的选择。如果您更喜欢坚持使用BoxLayoutFixing Alignment Problems一文讨论了这个问题,建议“由从左到右的 Boxlayout 控制的所有组件通常应该具有相同的 Y 对齐方式。” 在您的示例中,添加

botSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
blindSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
于 2010-03-11T16:54:53.917 回答
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));

或者我想是的;-)

于 2010-03-11T14:10:11.557 回答