I want to use the following code:
File file = new File("/home/marco/eclipse-workspace/Spielwiese/RKI2019_Diabetesbericht.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
to open a PDF-file in a webbrowser. I need this code in another Java class which does not extend Application. In the following link is a good description how to do it but it does not fit properly because I am not using a fxml-file: JavaFx 8: open a link in a browser without reference to Application
I want to have two classes. The main class (which is extending Application) and another one which is not extending Application. In this second class I want to click on a button which than opens the PDF file. Can someone please help me with this issue. I am new to JavaFX and tried really hard but didnt get it to work. Thanks in advance! :) Following code I produced so far:
Main-Class:
package application;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
VBox root = new VBox();
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
Button button = new Button("Press me");
root.getChildren().add(button);
HostServices hostServices = getHostServices();
button.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent e) {
Test.create(primaryStage, hostServices);
}
});
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Other Class:
package application;
import java.io.File;
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.GridPane;
import javafx.stage.Stage;
public class Test {
public static void create (Stage stage, HostServices hostServices){
GridPane secondarygridpane = new GridPane();
Scene scene2 = new Scene(secondarygridpane,400,400);
Button button = new Button ("Press me");
secondarygridpane.add(button, 0, 0);
button.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent e) {
File file = new File("/home/marco/eclipse-workspace/Spielwiese/RKI2019_Diabetesbericht.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
}
});
stage.setScene(scene2);
stage.show();
}
}
If i click on the button a pdf-file should open.