Search code examples
javaswingjpanellayout-managergridbaglayout

Concatenating JPanels vertically while keeping their setPreferredSize() sizes


I'd like to have a "list" of concatenated JPanels in which each cell has the corresponding JPanel's size. For example:

enter image description here

In this example the setPreferredSize of Panel1 is smaller than the one of Panel2. The result of concatenating the JPanels is the above image.

I thought about making a gridbaglayout but I couldn't find a way to keep the dimension of setPreferredSize of each Panel... For now what I have is weight ratio between the cells...

    gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{0, 0};
    gridBagLayout.rowHeights = new int[]{0, 0, 0};
    gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{1.0, 9.0, Double.MIN_VALUE};
    setLayout(gridBagLayout);

    p1 = new Panel1();
    p2 = new Panel2();      
    GridBagConstraints gbc_p1 = new GridBagConstraints();
    gbc_p1.insets = new Insets(0, 0, 0, 0);
    gbc_p1.fill = GridBagConstraints.BOTH;
    gbc_p1.gridx = 0;
    gbc_p1.gridy = 0;
    add(p1, gbc_p1);



    GridBagConstraints gbc_p2 = new GridBagConstraints();
    gbc_p2.fill = GridBagConstraints.BOTH;
    gbc_p2.gridx = 0;
    gbc_p2.gridy = 1;
    add(p2, gbc_p2);

Solution

  • I just want to concatenate The JPanels one after another vertically and to keep their setPreferredSize() size

    A GridBagLayout will respect the preferred size of a component.

    Just don't use the "fill" constraint.