Swing中如何实现两个BoxLayout布局容器横向并排展示
问题原因
你之前直接将根容器pane的布局设为了垂直排列的BoxLayout.Y_AXIS,所有加入根容器的组件都会纵向堆叠,自然无法实现两个垂直面板横向并排的效果。
解决方案
调整容器层级结构,将两个垂直布局的面板作为子组件,加入横向排列的根容器即可,具体修改如下:
- 核心功能按钮不再直接加到根容器,单独放到一个垂直布局的
JPanel中 - 修改辅助按钮面板的构造方法,返回构造完成的
JPanel实例 - 根容器改用横向排列的布局,将两个垂直面板依次加入即可实现并排效果
完整修改后代码
private static void contentGUI(Container pane) throws IOException, FontFormatException { // 根容器设置为横向排列 pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); // 构造左侧核心功能面板(保持垂直排列) JPanel funcPanel = new JPanel(); funcPanel.setLayout(new BoxLayout(funcPanel, BoxLayout.Y_AXIS)); JButton task1 = new JButton(" > Advanced CPU Settings"); funcPanel.add(task1); JButton task2 = new JButton(" > Advanced Memory Settings"); funcPanel.add(task2); JButton task3 = new JButton(" > Advanced GPU Settings"); funcPanel.add(task3); JButton task4 = new JButton(" > Advanced Case Fan Settings"); funcPanel.add(task4); // 获取右侧辅助功能面板 JPanel toolTipPane = createToolTipPane(); // 两个面板加入根容器实现横向并排,可添加水平间距优化显示 pane.add(funcPanel); pane.add(Box.createHorizontalStrut(20)); pane.add(toolTipPane); } // 原toolTips方法调整为返回构造好的辅助面板 private static JPanel createToolTipPane() throws IOException, FontFormatException { JPanel toolTipPane = new JPanel(); toolTipPane.setLayout(new BoxLayout(toolTipPane, BoxLayout.Y_AXIS)); JButton tip1 = new JButton("Esc: Exit"); toolTipPane.add(tip1); JLabel tip2 = new JLabel("F1: About"); toolTipPane.add(tip2); return toolTipPane; }
效果适配优化
如果要实现你给出的预期效果图中「左侧功能区占满剩余宽度、右侧辅助区固定宽度」的效果,将根容器布局改为BorderLayout即可:
// 替换根容器的BoxLayout设置为BorderLayout pane.setLayout(new BorderLayout()); pane.add(funcPanel, BorderLayout.CENTER); pane.add(toolTipPane, BorderLayout.EAST);
内容的提问来源于stack exchange,提问作者Chaitanya S
相关产品推荐
相关产品推荐

