Search code examples
javaswingjpanelgridbaglayoutpreferredsize

Filling a content pane with panels


Im setting the content pane of a JFrame to a panel that I've created. This panel makes use of the Grid Bag Layout for its subsequent panels. I set this layout like so:

private void initPanel() {

    setLayout(new GridBagLayout());
    constraints = new GridBagConstraints();
    populateGUI();
}

This causes the "game" to like like this:

enter image description here

What I'm actually trying to do is to expand those panels (the tiny squares) out. The dimensions of the JFrame are 800 x 500, so each panel should occupy 100 x 100 making a total of 40 panels. The problem is that the panels are just too small as they are.

I populate the content pane of the JFrame (replaced by own panel - marked in red) with this code:

private void populateGUI() {

    // Fill the frame with panels
    for (int rowPos = 0; rowPos < numColumns; rowPos++) {

        for (int colPos = 0; colPos < numRows; colPos++) {

            constraints.gridx = rowPos;
            constraints.gridy = colPos;

            // Add component
            add(new GameDummyPanel(gameUtil.generateRandomColour(),
                    panelWidth, panelHeight), constraints);
        }
    }
}

Note - those are the only constraints that I implement. In the GameDummyPanel class i set the size using the following:

    public GameDummyPanel( Color panelColor, int panelWidth, int panelHeight )
{
    dummyPanelWidth = panelWidth / 8;
    dummyPanelHeight = panelHeight / 5;

    setBackground( panelColor );
    setSize( new Dimension( dummyPanelWidth, dummyPanelHeight ) );
}

so why isn't this being enforced? Its not like I'm calling pack on the panel and on the panel that acts as the content pane of the JFrame.

Thanks

Update

Having examined and implemented the answers what needed to be done - should you not want to read below - is to set the fill property of the contraints to BOTH and remove all size based properties from the panel class. This means my constraints look like this:

    constraints = new GridBagConstraints();
    constraints.weightx = 1.0;
    constraints.weighty = 1.0;
    constraints.fill = GridBagConstraints.BOTH;

Minus the actually unique positioning for each of the panels set up gridx and gridy. the JPanel implementation could then actually be done away with and have the JPanel just created on the fly.


Solution

  • Try with some more properties of GridBagConstraints.

     constraints.weightx=1.0;
     constraints.weighty=1.0;
     constraints.fill=GridBagConstraints.BOTH;
    

    OR

    Use GridLayout instead of GridBagLayout in this case.

    private void initPanel() {
        setLayout(new GridLayout(numRows, numColumns));
        populateGUI();
    }
    

    enter image description here