32

我正在尝试从 javafx 在默认系统浏览器中打开一个 web url。我没有找到任何有关此的官方文档。有什么线索吗?

编辑:我找到了一个教程,但它不起作用。我正在使用 MacOsX 并尝试启动

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

但我得到一个HeadlessExcelption

4

6 回答 6

44

使用hostServices.showDocument(location)

尝试将以下代码放在应用程序的 start 方法中:

getHostServices().showDocument("http://www.yahoo.com");
于 2013-05-17T18:09:40.447 回答
16

补充jewelsea的答案,如果你不知道如何调用 getHostServices() 然后在你的主课上试试这个:

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

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

于 2014-05-23T18:33:47.423 回答
11

另一种选择是使用ProcessBuilder

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

如果Desktop.getDesktop().browse(uri)由于某种原因挂起而没有任何错误,您可以使用此选项。

于 2014-08-23T08:47:31.097 回答
7

尝试这个:

try {
    Desktop.getDesktop().browse(new URL("https://google.com").toURI());
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
于 2017-12-05T03:50:26.740 回答
2

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.

于 2013-05-17T12:42:48.483 回答
1

这是一个在场景控制器中工作的脚本,当一个按钮被激活时:

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 {

    }
}
于 2016-12-08T15:06:11.297 回答