How can I open the default system browser from a j

2019-01-09 08:19发布

I'm trying to open a web url in the default system browser from javafx. I didn't find any official documentation regard this. Any clue?

EDIT: I've found a tutorial but it doesn't work. I'm using MacOsX and I tried launching

java.awt.Desktop.getDesktop().browse(new URI(url));

but I get an HeadlessExcelption

6条回答
淡お忘
2楼-- · 2019-01-09 08:48

Here is a script that works inside the scene controller, when a button is activated:

package sample;


import com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory;
import com.sun.javafx.application.HostServicesDelegate;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;

public class Controller extends Application {

    public void openBrowser(ActionEvent actionEvent) throws Exception {

        HostServicesDelegate hostServices = HostServicesFactory.getInstance(this);
        getHostServices().showDocument("http://www.yahoo.com");

    }

    @Override
    public void start(Stage primaryStage) throws Exception {

    }
}
查看更多
贪生不怕死
3楼-- · 2019-01-09 08:49

Complementing jewelsea's answer, if you don't know how to call getHostServices() then try this at your main class:

HostServicesDelegate hostServices = HostServicesFactory.getInstance(this);
hostServices.showDocument(WEBSITE);

http://docs.oracle.com/javafx/2/api/javafx/application/HostServices.html#showDocument(java.lang.String)

查看更多
ら.Afraid
4楼-- · 2019-01-09 08:53

Use hostServices.showDocument(location).

Try placing the following code in your application's start method:

getHostServices().showDocument("http://www.yahoo.com");
查看更多
闹够了就滚
5楼-- · 2019-01-09 09:03

Try This:

try {
    Desktop.getDesktop().browse(new URL("https://google.com").toURI());
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
查看更多
够拽才男人
6楼-- · 2019-01-09 09:04

Another option is to use ProcessBuilder:

public static void openWebpage(String url) {
    try {
        new ProcessBuilder("x-www-browser", url).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

You can use this option if Desktop.getDesktop().browse(uri) for some reason hangs without any error.

查看更多
三岁会撩人
7楼-- · 2019-01-09 09:04

It cannot be done, seems, because this feature is not implemented : https://javafx-jira.kenai.com/browse/RT-210

The matter is that you will not be able to launch anything, what requires awt-stack and jfx in the same VM. The decision - is to use a separate JVM. Just launch a separate VM, and accept commands on browsing by socket.

That is one way, another way - is to find any other way of browser call from java - this is a task not specific to javafx-2, but to java at all.

But developer has added a comment :

Anthony Petrov added a comment - May, 17 2013 05:09 PM Note that FX8 allows headful AWT to run in the same VM with FX. So the AWT API should work.

查看更多
登录 后发表回答