使BoxLayout从左到右堆叠时将组件移动到顶部

Aly*_*Aly 6 java user-interface swing layout-manager

我有一个JPanel它使用BoxLayoutX_AXIS方向.我的问题最好通过图像显示: alt text http://www.freeimagehosting.net/uploads/fbffd71119.png

如您所见,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);
}
Run Code Online (Sandbox Code Playgroud)

tra*_*god 5

Riduidel关于设置本身是正确setAlignmentYGameSelectionPanelGridBagLayout是一个很好的选择。如果您更愿意坚持使用BoxLayout,文章Fixing Alignment Problems讨论了这个问题,建议“由从左到右的 Boxlayout 控制的所有组件通常应该具有相同的 Y 对齐。” 在您的示例中,添加

botSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
blindSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
Run Code Online (Sandbox Code Playgroud)


Rid*_*del 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));
Run Code Online (Sandbox Code Playgroud)

或者我认为是这样;-)