Is there any way to force GridLayout to leave empty cells?

Pentarctagon picture Pentarctagon · Feb 2, 2014 · Viewed 25.5k times · Source

I have a JTabbedPane with 2 JPanels set to GridLayout(13, 11). The first JPanel has enough of the cells filled out that it leaves the empty cells. enter image description here

The second JPanel has significantly fewer cells filled and this results in each button getting stretched to fill an entire row. enter image description here

Is there any way to get GridLayout to honor the empty cells, so the buttons in both JPanels are the same size?

Answer

Paul Samsotha picture Paul Samsotha · Feb 2, 2014

Use nested layouts to get your desired result. Some layouts respect the preferred size of components and some don't. GridLayout is one of the ones that don't. Have a look at this answer to see which one's do and which one's don't.

For example, you could nest the 13 buttons in a GridLayout nested in another JPanel with a FlowLayout

JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel p2 = new JPanel(new GridLayout(13, 1));
for (int i = 0; i < 13; i++) {
    p2.add(new JButton("Button " + i));
}
p1.add(p2);

enter image description here

import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test6 {

    public Test6() {
        JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
        JPanel p2 = new JPanel(new GridLayout(13, 1));
        for (int i = 0; i < 13; i++) {
            p2.add(new JButton("Button " + i));
        }
        p1.add(p2);

        JFrame frame = new JFrame("Test Card");
        frame.add(p1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test6 test = new Test6();
            }
        });
    }
}