Java 使BoxLayout在从左到右堆叠的同时将组件移动到顶部
我有一个Java 使BoxLayout在从左到右堆叠的同时将组件移动到顶部,java,user-interface,swing,layout-manager,Java,User Interface,Swing,Layout Manager,我有一个JPanel,它在X_轴方向使用BoxLayout。我遇到的问题最好通过一张图片来说明: 如您所见,左侧的JPanel已居中,而不是在顶部对齐。我希望它们都在顶部对齐并从左到右堆叠,如何使用此布局管理器实现这一点?我写的代码如下: public GameSelectionPanel(){ setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setAlignmentY(TOP_ALIGNMENT); setBo
JPanel
,它在X_轴方向使用BoxLayout
。我遇到的问题最好通过一张图片来说明:
如您所见,左侧的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);
}
嗯,setAlignmentY
方法在这里没有效果,因为它作用于被视为组件的面板
正如您所猜测的,所包含面板的布局由您使用的布局管理器定义。
不幸的是,BoxLayout
没有提供您所看到的功能
显然,在标准JDK中,为您的问题选择的布局是GridBagLayout
。虽然一开始很难理解,但它会很快向您展示它在组件排列方面的威力
使用有用的类,您的组件可以按如下方式排列:
setLayout(new GridBagLayout(this));
add(botSelectionPanel, new GBC(0,1).setAnchor(TOP));
add(blindSelectionPanel, new GBC(0,2).setAnchor(TOP));
或者我认为是这样;-) 在GameSelectionPanel
本身上设置setAlignmentY
是正确的,而GridBagLayout
是一个很好的选择。如果您更愿意坚持使用BoxLayout
,本文将对此进行讨论,建议“由左到右的BoxLayout控制的所有组件通常应具有相同的Y对齐方式。”在您的示例中,添加
botSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
blindSelectionPanel.setAlignmentY(JPanel.TOP_ALIGNMENT);
哇,伙计,关于GBC课程的链接不错。虽然我开始使用GridBagConstraints完整构造函数。我学习了参数位置。但对于小型GUI来说,GBC是一条出路。对于较大的GUI,我认为一行完整的GridBagConstraints构造函数是最好的解决方案。GridBagLayout构造函数没有输入参数您的示例在线程“AWT-EventQueue-0”java.lang.IllegalArgumentException中出现异常:非法锚定值