我的JPanel中具有GridBagLayout的组件对齐存在问题。 JLabel位于顶部,但未居中,下方的JButtons一直位于右侧。有什么方法可以将它们放在中心吗?这是我初始化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);
}
答案 0 :(得分:3)
这是您的代码,其形式有效。为了使其有效,您需要做以下事情:
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();
c.fill=GridBagConstraints.BOTH;
c.anchor=GridBagConstraints.CENTER;
welcome.setText("Welcome to rock paper scissors! Please enter your move.");
welcome.setHorizontalAlignment(SwingConstants.CENTER);
c.weightx=1;
c.gridy = 0; c.gridx = 0; c.insets = new Insets(10, 0, 0, 0);
c.gridwidth=moveChoices.length;
c.gridheight=1;
buttonsPanel.add(welcome,c);
c.insets=new Insets(0,0,0,0);
c.gridwidth=1;
for(int i = 0; i < moveChoices.length; i++) {
moveChoices[i] = new JButton();
c.gridx = i;
c.gridy = 1;
c.weightx=0.5;
c.weighty=1;
moveChoices[i].addActionListener(this);
buttonsPanel.add(moveChoices[i], c);
}
moveChoices[0].setText("Rock");
moveChoices[1].setText("Paper");
moveChoices[2].setText("Scissors");
this.add(buttonsPanel);
}