如何在JScrollPane中添加多个JPanel且不出现面板覆盖问题
解决方案
问题根源
JScrollPane的视口(Viewport)设计上仅支持承载单个组件,多次调用viewport.add()会覆盖之前添加的组件;且JScrollPane本身的布局管理器固定为ScrollPaneLayout,强制修改会抛出异常。
实现方法
你需要先创建一个中间JPanel作为容器,将所有需要展示的自定义JPanel都添加到这个中间容器中,再将中间容器整体放入JScrollPane的视口即可。
修改后的代码示例
VistaFCFS 构造方法调整
public VistaFCFS() throws HeadlessException { super("Tittle"); this.setSize(1400, 500); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setResizable(false); this.setLocationRelativeTo(null); // 创建中间容器承载多个JPanel JPanel contentPanel = new JPanel(); // 此处设置为垂直排列布局,可根据需求更换为其他布局(如横向排列的BoxLayout.X_AXIS、GridLayout等) contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); // 添加所有需要展示的自定义JPanel contentPanel.add(new MainTable()); contentPanel.add(new MainProcess()); // 将中间容器整体放入JScrollPane视口 panelScroll.setViewportView(contentPanel); this.setContentPane(panelScroll); }
可选调整项
- 如需两个面板横向排列,将BoxLayout的参数改为
BoxLayout.X_AXIS即可 - 如需两个面板均分窗口高度,可将中间容器的布局改为
new GridLayout(2, 1) - 如需面板之间保留间距,可在两次
add()操作之间插入contentPanel.add(Box.createVerticalStrut(10))设置10像素的垂直间隔 - 当中间容器的总高度/宽度超出JScrollPane视口范围时,滚动条会按照你预设的规则自动弹出
内容的提问来源于stack exchange,提问作者Smooth Researcher
相关产品推荐
相关产品推荐

