【问题标题】:How to open a PDF file javafx如何打开 PDF 文件 javafx
【发布时间】:2016-04-30 22:15:24
【问题描述】:

我想打开一个 pdf 文件并在单击按钮时将其显示在新窗口中 我试试这个,它不起作用:

Button btn = new Button();

File file=new File("Desktop/Test.pdf");
btn.setText("Open");

btn.setOnAction(new EventHandler<ActionEvent>() {

    public void handle(ActionEvent event) {

        try {
            desktop.open(file);
        } catch (IOException ex) {
            Logger.getLogger(Exemple.class.getName())
                .log(Level.SEVERE, null, ex);
        }
    }
});

【问题讨论】:

  • 什么是desktop? “不工作”是什么意思?
  • 桌面桌面 = Desktop.getDesktop();
  • 找不到文件,但我把它放在桌面上
  • 试试new File(System.getProperty("user.home"), "Desktop/Test.pdf")

标签: java pdf javafx javafx-8


【解决方案1】:

您可以尝试用这种方式打开 PDF 文件:

File file = new File("C:/Users/YourUsername/Desktop/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());

如果你想使用 FileChooser,那么使用这个:

btn.setOnAction(new EventHandler<ActionEvent>()
{
    @Override
    public void handle(ActionEvent event)
    {
        FileChooser fileChooser = new FileChooser();

        // Set Initial Directory to Desktop
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop"));

        // Set extension filter, only PDF files will be shown
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf");
        fileChooser.getExtensionFilters().add(extFilter);

        // Show open file dialog
        File file = fileChooser.showOpenDialog(primaryStage);

        //Open PDF file
        HostServices hostServices = getHostServices();
        hostServices.showDocument(file.getAbsolutePath());
    }
});

【讨论】:

  • getHostServices 方法体在哪里?
  • @orion_IX, getHostServices()HostServices 类的默认方法。只需在您的班级中导入javafx.application.HostServices,您就会找到答案。
  • 澄清这一点,因为我也遇到了问题:getHostServices() 是您的 JavaFX 主类 public class ... extends Application {ApplicationAPI 的方法,因此您只能在此处实例化它.如果您在另一个 Java 类中需要它,则必须像 here 所示那样传递它。
【解决方案2】:

如果您使用的是 windows,则需要像这样修复文件的路径:

File file=new File("C:\\Users\\USER\\Desktop\\Test.pdf");

您需要将 USER 更改为您的 windows 用户。

另外,请注意\ 用于编程语言中的转义序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 2016-03-06
    • 2017-05-27
    • 2013-02-10
    • 2012-10-10
    • 2014-06-30
    • 2015-07-12
    • 2016-08-09
    相关资源
    最近更新 更多