Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open External Application From JavaFX

I found a way to open a link on default browser using HostServices.

getHostServices().showDocument("http://www.google.com");
  • Is there any way to open a media in default media player?
  • Is there any way to launch a specific File or Application?
like image 432
Rana Depto Avatar asked Dec 03 '22 23:12

Rana Depto


1 Answers

Generally speaking, you can use Desktop#open(file) to open a file natively as next:

final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.OPEN)) {
    desktop.open(file);
} else {
    throw new UnsupportedOperationException("Open action not supported");
}

Launches the associated application to open the file. If the specified file is a directory, the file manager of the current platform is launched to open it.

More specifically, in case of a browser you can use directly Desktop#browse(uri), as next:

final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
    desktop.browse(uri);
} else {
    throw new UnsupportedOperationException("Browse action not supported");
}

Launches the default browser to display a URI. If the default browser is not able to handle the specified URI, the application registered for handling URIs of the specified type is invoked. The application is determined from the protocol and path of the URI, as defined by the URI class. If the calling thread does not have the necessary permissions, and this is invoked from within an applet, AppletContext.showDocument() is used. Similarly, if the calling does not have the necessary permissions, and this is invoked from within a Java Web Started application, BasicService.showDocument() is used.

like image 115
Nicolas Filotto Avatar answered Dec 27 '22 01:12

Nicolas Filotto