在JavaFX中使用关联程序打开PDF文件

3

我希望我的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);
    }
}

那么问题出在哪里呢?它是否崩溃了?它是否做了与您预期不同的事情?请详细解释一下确切的问题是什么。 - n247s
1个回答

3
如果PDF文件与调用者文件在同一个包中(如您所述),那么,
getHostServices().showDocument(getClass()
    .getResource("computer_graphics_tutorial.pdf").toString());

需要解决问题。

getResource 方法可用于灵活定位文件。这里是如何使用该方法的简短描述:JavaFX 资源处理:在 WebView 中加载 HTML 文件


@ DVarga 谢谢。它有效。我只想知道一件事。如果我在我的控制器类中使用 getHostServices(),它就不起作用。为什么会这样?示例在此:public void initialize(URL location, ResourceBundle resources) {} - mistletoe
我猜测控制器在另一个包中,因此您必须更新getResource调用以正确定位文件。答案中的链接可以帮助您了解如何在项目结构中定位文件。 - DVarga
@ DVarga 非常感谢!:) - mistletoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接