Reputation: 47
I am having an issue with the alignment of components in my JPanel which has a GridBagLayout. The JLabel is on the top, but not centered, and the JButtons underneath are positioned all the way to the right. Is there any way I can position them both in the center? Here is the method in which I initialize my 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);
}
Upvotes: 2
Views: 9271
Reputation: 1441
Here is your code in a form that works. To make it work, you need to to the following things:
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);
}
Upvotes: 5