我的 JPanel 中有一个 GridBagLayout 的组件对齐问题。JLabel 位于顶部,但未居中,下方的 JButton 一直位于右侧。有什么办法可以把它们都放在中间吗?这是我初始化 GUI 的方法。
public void initialize() {
JButton[] moveChoices = new JButton[3];
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBackground(Color.green);
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel welcome = new JLabel();
for(int i = 0; i < moveChoices.length; i++) {
moveChoices[i] = new JButton();
c.gridx = i;
c.gridy = 1;
if (i == 0) c.anchor = GridBagConstraints.EAST;
if (i == 2) c.anchor = GridBagConstraints.WEST;
moveChoices[i].addActionListener(this);
buttonsPanel.add(moveChoices[i], c);
}
moveChoices[0].setText("Rock");
moveChoices[1].setText("Paper");
moveChoices[2].setText("Scissors");
welcome.setText("Welcome to rock paper scissors! Please enter your move.");
c.gridy = 0; c.gridx = 1; c.insets = new Insets(10, 0, 0, 0);
buttonsPanel.add(welcome);
winText = new JLabel();
buttonsPanel.add(winText, c);
this.add(buttonsPanel);
}