Pregunta

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);
¿Fue útil?

Solución

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.

Otros consejos

Instead of the good-old GridBaglayout I have a suggestion with BoxLayout.

public class PanelTower extends JFrame {

    int length = 4 ;

    public PanelTower() {

        JPanel towerPanel = new JPanel();
        towerPanel.setLayout(new BoxLayout(towerPanel, BoxLayout.Y_AXIS));

        JPanel[] panels = new JPanel[length];
        for (int i = 0; i < length; i++) {
            panels[i] = new JPanel();
            panels[i].setBackground(new Color((float)Math.random(), (float)Math.random(), (float)Math.random()));
            Dimension dims = new Dimension((i+1)*50, (i+1)*50);
            panels[i].setPreferredSize(dims);
            panels[i].setMinimumSize(dims);
            panels[i].setMaximumSize(dims);
            towerPanel.add(panels[i]);
        }

        add(towerPanel);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        new PanelTower();
    }
}

I'm not sure about your exact requirements, but this should be easily modifiable (I suspect from your example that the width is constant and only the height changes).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top