gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:33 28 4
gpt4 key购买 nike

我有一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com