user3220381
user3220381

Reputation: 547

Resizing the panels on gridlayout

I'm trying to make a simple ui game with Java swing. Here is my target layout design: (all panels have same width, excuse my drawing)

layout design

I need 3 small height panel and 1 large panel

I used GridLayout with 4x1. I added some buttons to first panel.

mainFrame = new JFrame("Basket Game");
mainFrame.setLayout(new GridLayout(4, 1));


options = new JPanel();
options.setLayout(new FlowLayout());
options.setBorder( new TitledBorder("Options Menu") );

options.add(settings);
options.add(start);
options.add(pause);
options.add(reset);
options.add(exit);

mainFrame.add(options);

But it makes the first panel too big.

form

How can I set a size for these panels or should I use different layout pattern.

Upvotes: 2

Views: 4912

Answers (1)

Arnaud
Arnaud

Reputation: 17524

With a GridLayout, all cells in the grid have the same size, that's why your panel has 1/4 of the total height.

You may consider using a vertical BoxLayout:

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
// add the panels to mainPanel, then
mainFrame.setContentPane(mainPanel);

Here is an example, with three panels containing one button each, and one panel having a bigger size :

        JFrame frame = new JFrame();

        JPanel p1 = new JPanel();
        p1.add(new JButton("11111"));
        JPanel p2 = new JPanel();
        p2.add(new JButton("222222"));
        JPanel p3 = new JPanel();
        p3.add(new JButton("3333"));
        JPanel p4 = new JPanel();
        p4.setPreferredSize(new Dimension(50, 400));

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

        mainPanel.add(p1);
        mainPanel.add(p2);
        mainPanel.add(p3);
        mainPanel.add(p4);

        frame.setContentPane(mainPanel);
        frame.pack();
        frame.setVisible(true);

Upvotes: 4

Related Questions