【问题标题】:Open PDF file with associated program in JavaFX在 JavaFX 中打开带有关联程序的 PDF 文件
【发布时间】:2017-05-27 07:14:22
【问题描述】:

我想要我的 java 应用程序,如果用户选择单击一个按钮,PDF 将使用计算机中安装的默认 PDF 阅读器打开。 我要打开的 PDF 存在于同一个包“应用程序”中。

我使用的代码是

 package application;

import java.io.File;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;


public class Main extends Application {

    @Override
    public void start(final Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Load PDF");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                File pdfFile = new File("computer_graphics_tutorial.pdf");
                getHostServices().showDocument(pdfFile.toURI().toString());
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);


        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

【问题讨论】:

  • 那么问题出在哪里?它会崩溃吗?它做的事情是否与您的预期不同?请多解释一下确切的问题是什么。

标签: java file pdf javafx


【解决方案1】:

如果 PDF 文件与调用方文件位于同一包中(如您所述),则

getHostServices().showDocument(getClass()
    .getResource("computer_graphics_tutorial.pdf").toString());

应该能解决问题。

getResource 方法可以非常灵活地用于定位文件。下面是如何使用它的小说明:JavaFX resource handling: Load HTML files in WebView.

【讨论】:

  • @DVarga 谢谢。有用。我只想知道一件事。如果我在控制器类中使用 getHostServices() 它不起作用。为什么会这样?这里面的例子:public void initialize(URL location, ResourceBundle resources) {}
  • 我猜控制器在另一个包中,因此您必须更新 getResource 调用才能正确定位文件。答案中的链接可帮助您如何在项目结构中找到文件。
  • @DVarga 非常感谢! :)
猜你喜欢
  • 2019-03-07
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多