Search code examples
javaswinggridjcomponentgridbaglayout

Java GridBagLayout with components inside


I am trying to get GridBagLayout with two panels to be 40% and 60% of the frame while being able to have components inside of them and it is being troublesome.

When I do not place the button inside the panel, it works just like I want it to.

Not quite sure what I am doing wrong and I have tried moving the creation of the button to where the panel on the GridBagLayout is created, but it still didn't work.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test{

public void display(){
    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(900,650);
    frame.setVisible(true);

    JPanel test = new JPanel();
    test.setLayout(new GridBagLayout());
    GridBagConstraints c= new GridBagConstraints();

    JPanel left= new JPanel();
    JPanel right= new JPanel();

    c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
    c.weightx = 0.4;
    c.gridx = 1;
    c.weighty = 1;
    test.add(left,c);
    c.weightx = .6;
    c.gridx = 2;
    test.add(right,c);

    JButton button= new JButton("A button");
    left.add(button,c);//If I do not add this, then it shows how I want it to be

    frame.add(test);
   }
}

Solution

  • The thing with the weights is that they describe what to do with the extra space. The components have their preferred, min and max dimensions which the layout manager uses when it calculates the layout. The GridBagLayout then splits the extra space using these weights. In your case, i think the space that is split equals 900-button.getPreferredSize().width. You are splitting maybe 800 pixels into 320 and 480.