JavaFx 8: open a link in a browser without reference to Application

前端 未结 3 1352
醉梦人生
醉梦人生 2020-12-09 05:37

Have got a Hyperlink. When clicked I want a link to be opened in an external browser.

The usual method cited on the web seems to be:

final Hyperlink         


        
3条回答
  •  失恋的感觉
    2020-12-09 05:52

    If you want to open a url when you click on a button inside your app and you are using an fxml controller file then you can do the following...

    First in your Main Application Startup file get a pointer to the HostServices object and add it to your stage such as...

    stage.getProperties().put("hostServices", this.getHostServices());
    

    Then in your fxml controller file get the hostServices object from the stage object and then execute the showDocument() method.

    HostServices hostServices = (HostServices)this.getStage().getProperties().get("hostServices");
    hostServices.showDocument("http://stackoverflow.com/");
    

    I have a method in my contoller class called getStage()...

    /**
     * @return the stage from my mainAnchor1 node.
     */
    public Stage getStage() {
        if(this.stage==null)
            this.stage = (Stage) this.mainAnchor1.getScene().getWindow();
        return stage;
    }
    

提交回复
热议问题