Reputation: 493
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);
}
}
Upvotes: 3
Views: 2862
Reputation: 21829
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.
Upvotes: 3