Search code examples
javaswinglayout-managergridbaglayout

How to set column width for GridBagLayout in Java


I want to create a layout looks like the attached picture. It has 2 panels. The left Panel with the minimum width is 500px, resizes when JFrame is resized. The right panel has a fixed width 120px. And there is a 10px padding between them.

I tried GridBagLayout but it seems not work as expected. Please help. Thank you.

enter image description here

    JPanel leftBox;
    JPanel rightBox;
    JButton btnSave;
    JButton btnRefresh;
    JTextArea txtArea;

    leftBox = new JPanel();
    rightBox = new JPanel();

    btnSave = new JButton("Save");
    btnRefresh = new JButton("Refresh");

    txtArea = new JTextArea();
    txtArea.setFont(new Font("Consolas", Font.BOLD, 14));

    leftBox.setLayout(new BoxLayout(leftBox, BoxLayout.Y_AXIS));
    leftBox.add(txtArea);

    rightBox.setLayout(new BoxLayout(rightBox, BoxLayout.Y_AXIS));
    rightBox.add(btnSave);
    rightBox.add(btnRefresh);

    this.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill  = GridBagConstraints.BOTH;
    this.add(leftBox, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill  = GridBagConstraints.BOTH;
    this.add(rightBox, gbc);

    txtArea.append("-------------");

enter image description here


Solution

    • It works if gbc.weightx = 1f; is used for the first constraint, and 0f is used for the second.
    • Also change txtArea = new JTextArea(); to something like txtArea = new JTextArea(15,20); to suggest an initial size.
    • Wrap the text area in a scroll pane for aesthetics and usability.
    • "a 10px padding between them" - use the Insets of the GridBagConstraints for that.

    Here is how it might look after implementing those suggestions.

    enter image description here

    ..and dragged wider.

    enter image description here