Search code examples
javaswingjpaneljlabel

Is it a simple way to fill a cell of GridBagLayout with a JPanel?


Is it a simple way to create a panel inside a BorderLayout which will fill a cell?

Here is a simple example, where I'd like the grey panel (pnlTitle) to be as wide as the containing cell (100 pixels), but I'd like to do it without something like pnlTitle.setPreferredSize(new Dimension(100, 20));

Here is the code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestCode2_InsideColumn {

public static void main(String[] args) {

    JFrame window = new JFrame("Test");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(400, 200);
    window.setMinimumSize(new Dimension(350, 150));

    JPanel panelMain = new JPanel(new BorderLayout());
    window.add(panelMain);

    JLabel labelN = new JLabel("North");
    panelMain.add(labelN, BorderLayout.NORTH);

    JLabel labelS = new JLabel("South");
    panelMain.add(labelS, BorderLayout.SOUTH);

    GridBagLayout innerLayout = new GridBagLayout();
    GridBagConstraints innerConstraints = new GridBagConstraints();

    //Second (and last) column won't have fixed size, so last number is useless
    innerLayout.columnWidths = new int[] {100, 100};

    JPanel innerPanel = new JPanel(innerLayout);
    innerPanel.setBackground(new Color(0, 220, 250));
    panelMain.add(innerPanel, BorderLayout.CENTER);

    innerConstraints.anchor = GridBagConstraints.NORTHWEST;
    innerConstraints.weightx = 0.0;
    innerConstraints.weighty = 0.0;
    innerConstraints.gridx = 0;
    innerConstraints.gridy = 0;

    JLabel lblTitle = new JLabel("Title");
    JPanel pnlTitle = new JPanel(new BorderLayout());
    pnlTitle.add(lblTitle);
    innerLayout.setConstraints(pnlTitle, innerConstraints);
    innerPanel.add(pnlTitle);

    innerConstraints.gridx = 1;
    innerConstraints.weightx = 1.0;
    innerConstraints.fill = GridBagConstraints.HORIZONTAL;
    JLabel lblDescription = new JLabel("Label");
    innerLayout.setConstraints(lblDescription, innerConstraints);
    innerPanel.add(lblDescription);

    window.setVisible(true);
}

}

Solution

  • Try

    innerConstraints.fill = GridBagConstraints.BOTH
    

    From the JavaDocs

    BOTH
    public static final int BOTH
    Resize the component both horizontally and vertically.