3

I want my java application such that if user chooses to click on a button the PDF opens using the default PDF reader that is installed in the computer. The PDF which i want to be opened is present in same package "application".

The code which I am using is

 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);
    }
}
DVarga
  • 21,311
  • 6
  • 55
  • 60
mistletoe
  • 463
  • 4
  • 11
  • 29
  • So what is the problem? Does it crash? Is it doing something different from what you expected? Please explain a bit more what the exact problem is. – n247s Jan 12 '17 at 09:12

1 Answers1

3

If the PDF file is in the same package as the caller file (as you state), then

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

should solve the problem.

The getResource method can be used really flexibly to locate files. Here is a small description how to use it: JavaFX resource handling: Load HTML files in WebView.

Community
  • 1
  • 1
DVarga
  • 21,311
  • 6
  • 55
  • 60
  • @ DVarga Thanks. It works. I just want to know one more thing.If I use getHostServices() in my controller class it does'nt work. Why is it so? Example inside this : public void initialize(URL location, ResourceBundle resources) {} – mistletoe Jan 12 '17 at 10:08
  • I guess the controller is in another package, therefore you have to update the `getResource` call to propertly locate the file. The link in the answer helps you how to locate a file in your project structure. – DVarga Jan 12 '17 at 10:10
  • @ DVarga Thanks a lot! :) – mistletoe Jan 12 '17 at 11:25