Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

java - 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);
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • The default layout of a JFrame (or more specifically in this case, the content pane of the frame) is a BorderLayout.
  • When adding a component to a BordeLayout with no constraint, the Swing API will put the component in the CENTER.
  • A BorderLayout can contain exactly one component in each of the 5 layout constraints.
  • When a second component is added to the same (in this case CENTER) constraint of a BorderLayout, this implementation of Java will display the last component added.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...