javaswingjframelayout-managerborder-layout

Why does the first panel added to a frame disappear?


Below is an example of adding two panels to a frame. Only one panel (the 2nd, red panel) appears.

Disappearing Panel In Frame

Why does the first panel disappear?

import java.awt.Color;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class DisappearingPanelInFrame {

    DisappearingPanelInFrame() {
        JFrame f = new JFrame(this.getClass().getSimpleName());
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        f.add(getColoredPanel(Color.GREEN));
        f.add(getColoredPanel(Color.RED));

        f.pack();
        f.setVisible(true);
    }

    private JPanel getColoredPanel(Color color) {
        JPanel p = new JPanel();
        p.setBackground(color);
        p.setBorder(new EmptyBorder(20, 150, 20, 150));
        return p;
    }

    public static void main(String[] args) {
        Runnable r = DisappearingPanelInFrame::new;
        SwingUtilities.invokeLater(r);
    }
}

Solution

  • As to what would be a better approach depends on the specific needs of the user interface.