Hyperlink
A Hyperlink looks like a web link. When the user clicks it, you can open a website, change text, or perform any action.
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Hyperlink?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="15"
alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.example.demo.HelloController">
<Label text="Useful links:"/>
<Hyperlink fx:id="googleLink"
text="Open Google"
onAction="#openGoogle"/>
<Hyperlink fx:id="githubLink"
text="Open GitHub"
onAction="#openGitHub"/>
<Label fx:id="statusLabel"
text="No link clicked yet."/>
</VBox>
Controller
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import java.awt.Desktop;
import java.net.URI;
public class HelloController {
@FXML
private Hyperlink googleLink;
@FXML
private Hyperlink githubLink;
@FXML
private Label statusLabel;
@FXML
private void openGoogle() {
openWebsite("https://www.google.com");
statusLabel.setText("Google link clicked.");
}
@FXML
private void openGitHub() {
openWebsite("https://github.com");
statusLabel.setText("GitHub link clicked.");
}
private void openWebsite(String url) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch (Exception e) {
statusLabel.setText("Could not open: " + url);
e.printStackTrace();
}
}
}
What happens?
- Clicking
"Open Google"opens Google in the default browser. - Clicking
"Open GitHub"opens GitHub in the default browser. - The label changes to show which link was clicked.
More advanced example: one method for multiple links
Instead of making one method for every hyperlink, you can use a single method:
<Hyperlink text="Open Stack Overflow"
userData="https://stackoverflow.com"
onAction="#openLink"/>
<Hyperlink text="Open Oracle"
userData="https://oracle.com"
onAction="#openLink"/>
@FXML
private void openLink(ActionEvent event) {
Hyperlink clickedLink = (Hyperlink) event.getSource();
String url = clickedLink.getUserData().toString();
openWebsite(url);
statusLabel.setText("Opened: " + clickedLink.getText());
}
This is useful when you have many links.
Important methods
hyperlink.setText("My Link");
hyperlink.setVisited(true);
hyperlink.isVisited();
hyperlink.setDisable(true);
setVisited(true)changes the link color to the "visited" style.isVisited()checks whether the link was already clicked.