13 JavaFX Hyperlink
The JavaFX Hyperlink control is a text that functions as a button, meaning you can configure a Hyperlink to perform some action when the user clicks it. Just like a hyperlink in a web page. The JavaFX Hyperlink control is represented by the class javafx.scene.control.Hyperlink
.
Here is a screenshot showing how a JavaFX Hyperlink
looks:
JavaFX Hyperlink Example
Here is a full JavaFX Hyperlink example:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class HyperlinkExample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("JavaFX App"); Hyperlink link = new Hyperlink("Click Me!"); VBox vBox = new VBox(link); Scene scene = new Scene(vBox, 960, 600); primaryStage.setScene(scene); primaryStage.show(); } }
This example is a full JavaFX application that creates a Hyperlink
, inserts it into a JavaFX VBox which is then added to a JavaFX Scene. The Scene
is then added to a JavaFX Stage which is then made visible.
Create a Hyperlink
In order to use a JavaFX Hyperlink
control you must first create a Hyperlink
instance. Here is an example of creating a JavaFX Hyperlink
instance:
Hyperlink link = new Hyperlink("Click me!");
Set Hyperlink Text
It is possible to change the text of a JavaFX Hyperlink via its setText()
method. Here is an example of changing the text of a JavaFX Hyperlink:
Hyperlink link = new Hyperlink("Click me!"); link.setText("New link text");
Set Hyperlink Font
It is possible to change the font of a JavaFX Hyperlink via its setFont()
method. You can read more about creating fonts in my JavaFX Fonts tutorial. Here is an example of setting the font of a JavaFX Hyperlink:
Hyperlink link = new Hyperlink("Click Me!"); Font courierNewFontBold36 = Font.font("Courier New", FontWeight.BOLD, 36); link.setFont(courierNewFontBold36);
Set Hyperlink Action
To respond to clicks on a JavaFX Hyperlink
you set an action listener on the Hyperlink
instance. Here is an example of setting an action listener on a JavaFX Hyperlink
instance:
Hyperlink link = new Hyperlink("Click me!"); link.setOnAction(e -> { System.out.println("The Hyperlink was clicked!"); });