使用JTextField - Swing中的路径打开PDF文件

时间:2014-12-16 15:12:48

标签: java swing

拥有小型GUI,点击打开按钮,尝试打开本地存储的pdf文档,文件路径位于JTextField中。

enter image description here

我无法得到它,请给我一些指示,谢谢。

代码到目前为止;

        JButton btnEdi = new JButton("Open");
    btnEdi.setMnemonic('o');
    btnEdi.setFont(new java.awt.Font("Calibri", Font.BOLD, 12));
    btnEdi.setBorder(null);
    btnEdi.setBackground(SystemColor.menu);
    btnEdi.setBounds(378, 621, 35, 19);
    frmViperManufacturingRecord.getContentPane().add(btnEdi);

    btnEdi.addActionListener(new ActionListener(){
        //desktop = Desktop.getDesktop();
        //String storedFileName = txtText.getText();
        public void actionPerformed(ActionEvent ae) {
            desktop.open(txtText.getText());

        }
    });

2 个答案:

答案 0 :(得分:3)

在这一行:

btnEdi.addActionListener(new ActionListener() {
    @Override // don0t forget @Override annotation
    public void actionPerformed(ActionEvent ae) {
        desktop.open(txtText.getText()); // here
    }
});

根据Desktop#open(File file)方法文档,它需要File个对象作为参数,而不是String,所以我怀疑你的代码甚至编译。它还会抛出一个必须被处理的IOException

话虽这么说,这就是我要做的事情:

btnEdi.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        File pdfFile = new File(txtText.getText());                
        try {
            Desktop.getDesktop().open(pdfFile));
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog( null
                                         , "An error happened trying to open file : " + pdfFile.getPath()
                                         , "IOException"
                                         , JOptionPane.WARNING_MESSAGE
            );
        }
    }
});

另见How to Integrate with the Desktop Class教程。

答案 1 :(得分:0)

使用isDesktopSupported()方法确定您的操作系统上是否有Desktop API。

File pdfFile = new File("resources\\ManoeuvreRules-2010.pdf");   
if(isDesktopSupported()){
    try {
        Desktop.getDesktop().open(pdfFile);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog( null
                                     , "An error happened trying to open file : " + pdfFile.getPath()
                                     , "IOException"
                                     , JOptionPane.WARNING_MESSAGE
        );
    }
}
else{
    JOptionPane.showMessageDialog( null
                                     , "This is not supported on your Operating System: " 
                                     , "IOException"
                                     , JOptionPane.WARNING_MESSAGE
        );
}