Skip to content
Advertisement

Putting panels in a big Panel

I want to create a Frame with a big panel with flow layout which contains several smaller panels with a given size. I thought I could do like this: (The JFrame is given)

private void testLayout() {
    JPanel panel = new JPanel();
    panel.setBackground(Color.gray);
    add(panel);

    JPanel panel1 = new JPanel();
    panel1.setSize(300, 200);
    panel1.setBackground(Color.red);
    panel.add(panel1);
}

If I run this, I just get my big panel in gray and I only see a small red square in the top middle of my frame, although I set the size to 300px and 200px.

Advertisement

Answer

The displayed size of a component is determined by the layout manager. Some layout managers use the value returned by method getSize but not any of the ones that you are using in your code.

As you correctly stated, the default layout manager for JPanel is FlowLayout and FlowLayout actually uses the value returned by method getPreferredSize. Hence, rather than calling method setSize, call setPreferredSize. Below code demonstrates. (More explanations after the code.)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class PanelTst implements Runnable {
    private JFrame  frame;

    @Override
    public void run() {
        createAndDisplayGui();
    }

    private void createAndDisplayGui() {
        frame = new JFrame("Panels");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setBackground(Color.gray);
        JPanel panel1 = new JPanel();
        panel1.setPreferredSize(new Dimension(300, 200));
        panel1.setBackground(Color.red);
        panel.add(panel1);
        frame.add(panel);
        frame.setSize(450, 300);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new PanelTst());
    }
}

The default layout manager for the [content pane of] JFrame is BorderLayout. In the code in your question, you are actually adding panel to the center of BorderLayout which means that it will take up all the available space.

Since you don’t set any size for panel its size will be determined by the size of its parent. Hence, in my code, above, I explicitly set the size of the JFrame. Otherwise, you would only see panel1. (I suggest that you modify the above code and see for yourself. Replace frame.setSize(450, 300); with frame.pack();)

This is how it looks when I run the above code.

screen capture

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement