J doe J doe - 1 month ago 21
Java Question

GridBagLayout Jbutton Position

This is what I have :

enter image description here

and this is what I want to have :

enter image description here

Here's a piece of my code

container.add(conteneur2 , BorderLayout.EAST);


conteneur2.setBackground(Color.ORANGE);


conteneur2.setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();

JButton Bouton= new JButton("New remote site");

// Bouton 1

gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.LINE_START;

conteneur2.add(bouton,gbc);


So what's the problem?

Answer

You need to set the anchor NORTH

gbc.anchor = GridBagConstraints.NORTH;

and the y weight to 1 means all the free space is distributed in y direction.

gbc.weighty = 1;