Reputation: 347
I want to open a pdf file and display it on new window when a button is clicked i try this an it is not working:
Button btn = new Button();
File file=new File("Desktop/Test.pdf");
btn.setText("Open");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Exemple.class.getName())
.log(Level.SEVERE, null, ex);
}
}
});
Upvotes: 0
Views: 12543
Reputation: 721
You can try this way to open a PDF file:
File file = new File("C:/Users/YourUsername/Desktop/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
If you want to use FileChooser, then use this:
btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
FileChooser fileChooser = new FileChooser();
// Set Initial Directory to Desktop
fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop"));
// Set extension filter, only PDF files will be shown
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf");
fileChooser.getExtensionFilters().add(extFilter);
// Show open file dialog
File file = fileChooser.showOpenDialog(primaryStage);
//Open PDF file
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
}
});
Upvotes: 6
Reputation: 13
If you are using windows you need to fix the path of the file like this:
File file=new File("C:\\Users\\USER\\Desktop\\Test.pdf");
You need to change USER with your windows user.
Also, note that \
is used for escape sequences in programming languages.
Upvotes: 0