本文介绍了为什么添加到框架的第一个面板会消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是将两个面板添加到框架的示例.只出现一个面板(第二个,红色面板).
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.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);
}
}
推荐答案
JFrame
(或更具体地说,在本例中,框架的内容窗格)的默认布局是BorderLayout
.- 将组件添加到没有约束的
BordeLayout
时,Swing API 会将组件放在CENTER
中. - 一个
BorderLayout
可以在 5 个布局约束中的每一个中包含恰好一个的组件. - 当将第二个组件添加到
BorderLayout
的相同(在本例中为CENTER
)约束时,此 Java 实现将显示 添加的最后一个组件. - The default layout of a
JFrame
(or more specifically in this case, the content pane of the frame) is aBorderLayout
. - When adding a component to a
BordeLayout
with no constraint, the Swing API will put the component in theCENTER
. - 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 aBorderLayout
, 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.
这篇关于为什么添加到框架的第一个面板会消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!