我有一个使用
BoxLayout
在 X_AXIS
方向上的 JPanel
。最好通过一张图片来说明我的问题:
如您所见,左侧的 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);
}