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

时间:2010-03-11 13:52:53

标签: java user-interface swing layout-manager

我有一个JPanelBoxLayout方向使用了X_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);
}

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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));

或者我是这么认为的; - )