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

Java 使用JTextField-Swing中的路径打开PDF文件,java,swing,Java,Swing,使用小型GUI,单击打开按钮试图打开本地存储的pdf文档,文件路径位于JText字段中 我找不到,请给我指路,谢谢 到目前为止,守则 JButton btnEdi = new JButton("Open"); btnEdi.setMnemonic('o'); btnEdi.setFont(new java.awt.Font("Calibri", Font.BOLD, 12)); btnEdi.setBorder(null); btnEdi.set

使用小型GUI,单击打开按钮试图打开本地存储的pdf文档,文件路径位于JText字段中

我找不到,请给我指路,谢谢

到目前为止,守则

        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());

        }
    });
在这一行:

btnEdi.addActionListener(new ActionListener() {
    @Override // don0t forget @Override annotation
    public void actionPerformed(ActionEvent ae) {
        desktop.open(txtText.getText()); // here
    }
});
根据方法文档,它将对象作为参数,而不是
字符串
,因此我怀疑您的代码是否能够编译。它还抛出了一个必须处理的问题

尽管如此,我还是会这么做:

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
            );
        }
    }
});
另请参阅教程。

使用isDesktopSupported()方法确定桌面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
        );
}

也许这对你有帮助:谢谢@dic19,这是一个绝妙的解决方案!!非常感谢你。我的代码甚至没有编译,是抛出了一个错误,经过长时间的斗争后发布了它。现在成功了,再次感谢。欢迎:)我很高兴它帮助了@Java.初学者