Friday, April 29, 2022

Opening JavaFX hyperlinks in the browser

Suppose you have a hyperlink in your JavaFX application. Then you can make it clickable using the HostServices provided by JavaFX.
package application;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HyperLinkExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

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

        var linkLocation = "http://www.lisp-ai.blogspot.com";
        Hyperlink hp = new Hyperlink(linkLocation);
        var root = new StackPane();
        HostServices services = this.getHostServices();

        hp.setOnAction(new EventHandler() {
            @Override
            public void handle(ActionEvent actionEvent) {
                services.showDocument(linkLocation);
            }
        });

        root.getChildren().add(hp);
        Scene scene=new Scene(root,400,300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Clickable hyperlinks");
        primaryStage.show();

    }

}

The resulting JavaFX application looks like this: The idea of opening up a separate browser window for a hyperlink provides an alternative to using the JavaFX webview.

No comments:

Post a Comment