You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JInternalFrame嵌入PDF不显示问题求助(基于Apache PDFBox)

解决方案

1. 正确操作JInternalFrame的内容面板

Netbeans可视化设计的JInternalFrame默认自带内容面板,直接调用add()无法确保组件被正确添加,需通过getContentPane()操作:

// 先清空原有内容,避免重复添加组件导致显示混乱
jInternalFrame2.getContentPane().removeAll();
// 将滚动面板添加到内容面板
jInternalFrame2.getContentPane().add(new JScrollPane(label));

2. 强制触发界面更新

组件添加完成后,需要调用validate()和repaint()强制更新布局与渲染:

jInternalFrame2.setVisible(true);
jInternalFrame2.validate();
jInternalFrame2.repaint();

3. 释放PDF文档资源

PDFBox的PDDocument使用后必须关闭,否则会占用系统资源,甚至影响渲染逻辑:

finally {
    if (pdffile != null) {
        try {
            pdffile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 优化PDF渲染参数(可选)

若图片显示模糊或尺寸异常,可指定DPI参数提升渲染质量:

// 第二个参数为DPI值,示例设置为200
BufferedImage image = pdfRenderer.renderImageWithDPI(0, 200);

5. 检查JDesktopPane配置

确保jInternalFrame2已正确添加到主窗口的JDesktopPane中(Netbeans设计时需将JInternalFrame拖放至JDesktopPane),若手动添加需补充:

// 假设desktopPane为主窗口的JDesktopPane实例
desktopPane.add(jInternalFrame2);

完整修改代码

public void openFile(){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            PDDocument pdffile = null;
            try {
                File file = new File("/home/ritzmo/Labor_Clotten/PDF_Befunde/test.pdf");
                pdffile = Loader.loadPDF(file);
                PDFRenderer pdfRenderer = new PDFRenderer(pdffile);
                BufferedImage image = pdfRenderer.renderImageWithDPI(0, 200);
                JLabel label = new JLabel(new ImageIcon(image));
                
                jInternalFrame2.setTitle("PDF G");  
                jInternalFrame2.getContentPane().removeAll();
                jInternalFrame2.getContentPane().add(new JScrollPane(label));
                
                jInternalFrame2.setVisible(true);
                jInternalFrame2.validate();
                jInternalFrame2.repaint();
            } catch (IOException e) {
                e.printStackTrace(); // 打印异常便于排查问题
            } finally {
                if (pdffile != null) {
                    try {
                        pdffile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

内容的提问来源于stack exchange,提问作者Moritz Müller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:17:06