As I've read, it's really hard to treat to resize components inside GridLayout and GrigBagLayout. In my case, I have a GridBagLayout with 2 columns and 2 rows. In the first row there are 2 labels and in the second row there are 2 components (type Tablero
) which extend JTable.
My problem is, I can't make these 2 JTables fill the JFrame until its bottom. I've tried setSize(), setPreferredSize(), setBounds()
... but they don't work at all. I've also tried to do it by constraints.fill = GridBagConstraints.VERTICAL/SOUTH/CENTER
... but I get absolutly nothing.
I've also tried to set the size of the JPanel inside of the JFrame, but it doesn't work...
This is my code:
public static void main(String[] args)
{
JFrame pantalla = new JFrame();
pantalla.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
JLabel tab1Label = new JLabel("Tablero 1");
JLabel tab2Label = new JLabel("Tablero 2");
Tablero tablero1 = new Tablero();
Tablero tablero2 = new Tablero();
tablero1.setPreferredSize(new Dimension(400,400));
tablero1.setBounds(0, 0, 400, 400);
tablero1.setBorder(new LineBorder(Color.gray, 2));
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.insets = new Insets(0, 0, 20, 0);
pantalla.getContentPane().add(tab1Label, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.insets = new Insets(0, 0, 20, 0);
pantalla.getContentPane().add(tab2Label, constraints);
constraints.insets = new Insets(0, 0, 0, 0);
constraints.fill = GridBagConstraints.VERTICAL;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
pantalla.getContentPane().add(tablero1, constraints);
constraints.fill = GridBagConstraints.VERTICAL;
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
pantalla.getContentPane().add(tablero2, constraints);
pantalla.pack();
pantalla.setSize(800, 400);
pantalla.setVisible(true);
pantalla.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
And here is the result:
I know there are other ways easier to make it, but to use GridBagLayout is actually a requeriment.
Try to add constraints.weightx = 1;
and constraints.weighty = 1;
to your JTables constraints.
Also remove those lines:
tablero1.setPreferredSize(new Dimension(400,400));
tablero1.setBounds(0, 0, 400, 400);