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

标签 java user-interface swing layout-manager

我有一个 JPanel,它在 X_AXIS 方向上使用了一个 BoxLayout。我遇到的问题最好用一张图片展示: 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);
}

最佳答案

RiduidelGameSelectionPanel 本身上设置 setAlignmentY 是正确的,GridBagLayout 是一个很好的选择。如果您更喜欢使用 BoxLayout,文章 Fixing Alignment Problems讨论此事,建议“由从左到右的 Boxlayout 控制的所有组件通常应具有相同的 Y 对齐方式。”在您的示例中,添加

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

关于java - 使 BoxLayout 将组件移动到顶部,同时从左到右堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2425387/

相关文章:

windows - 是否可以在没有实际窗口的情况下在 Windows 操作系统上显示 "on screen"文本?

Android:TabSpec setContent(View) 中的 NPE

java - 如何调整 Jpanel 中 JTextField 的大小

java - dto 应该实现关联的接口(interface)吗?

java - 通过反射从 import static 获取类中的静态变量

java - 如何验证从 Cognito 获得的 jwt token

java - Maven 项目找不到 Groovy 类

python - PyQt - 窗口的位置

Java JPopupMenu Mac OS X

java - 全屏模式下的 JInternalFrame