Java Swing中JPanel嵌套实现及布局显示异常问题咨询
问题原因
你的代码存在3个核心问题:
- 使用
BorderLayout添加组件时未指定布局约束,默认会将组件放在CENTER区域,直接占满整个父面板,导致黄色的parentJpanel被完全遮挡 - 优先调用了
JFrame.setVisible(true)再添加组件,组件不会自动触发渲染刷新 - 在布局管理器接管容器尺寸控制的场景下,调用
setSize、setLocation不会生效,需要用setPreferredSize指定组件期望尺寸
修正后可运行代码
import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { //JFrame JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setSize(1920, 1080); jframe.setResizable(false); jframe.setLocationRelativeTo(null); //parentJpanel - 主面板 JPanel parentJpanel = new JPanel(); parentJpanel.setBackground(Color.YELLOW); parentJpanel.setLayout(new BorderLayout()); //smallPanel - 底部小面板 JPanel smallPanel = new JPanel(); smallPanel.setBackground(Color.GREEN); // 指定期望高度,宽度自动适配父容器 smallPanel.setPreferredSize(new Dimension(1920, 300)); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.PAGE_AXIS)); // 测试:给绿色面板加2个子面板验证嵌套效果,可根据需求替换为自己的业务组件 JPanel childPanel1 = new JPanel(); childPanel1.setBackground(Color.RED); childPanel1.setPreferredSize(new Dimension(1920, 100)); JPanel childPanel2 = new JPanel(); childPanel2.setBackground(Color.BLUE); childPanel2.setPreferredSize(new Dimension(1920, 100)); smallPanel.add(childPanel1); smallPanel.add(childPanel2); // 指定绿色面板放在父面板的南部(底部) parentJpanel.add(smallPanel, BorderLayout.SOUTH); jframe.add(parentJpanel); // 所有组件添加完成后再显示窗口 jframe.setVisible(true); } }
如果需要在绿色面板内放置更多不同尺寸、排列规则的子组件,可根据需求将BoxLayout替换为FlowLayout、GridLayout或者更灵活的GridBagLayout即可。
内容的提问来源于stack exchange,提问作者Martin Serdült
相关产品推荐
相关产品推荐

