为什么添加到框架的第一个面板消失了? [英] Why does the first panel added to a frame disappear?

查看:138
本文介绍了为什么添加到框架的第一个面板消失了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是向框架添加两个面板的示例。只显示一个面板(第二个红色面板)。

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

为什么第一个面板消失?

Why does the first panel disappear?

import java.awt.*;
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(new ColoredPanel(Color.GREEN));
        f.add(new ColoredPanel(Color.RED));

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

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

class ColoredPanel extends JPanel {

    ColoredPanel(Color color) {
        setBackground(color);
        setBorder(new EmptyBorder(20, 150, 20, 150));
    }
}


推荐答案


  • JFrame 的默认布局(或者更具体地说,在这种情况下,框架的内容窗格)是 BorderLayout

  • 在没有约束的情况下将组件添加到 BordeLayout 时, Swing API会将组件放入 CENTER

  • A BorderLayout 可以在5个布局约束中的每一个中都包含完全一个组件。

  • 当第二个组件添加到同一个组件时(在这种情况下 CENTER BorderLayout 的约束,这个Java实现将显示最后添加的组件。

    • 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.

      这篇关于为什么添加到框架的第一个面板消失了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆