The Hyperlink class represents the hyper links similar to the anchor links on the web pages in JavaFX.
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.layout.VBox; import javafx.stage.Stage; /*from w ww. j a v a 2 s . c o m*/ public class Main extends Application { @Override public void start(Stage stage) { stage.setTitle("HTML"); stage.setWidth(500); stage.setHeight(500); Scene scene = new Scene(new Group()); VBox root = new VBox(); Hyperlink link = new Hyperlink("www.java2s.com"); root.getChildren().addAll(link); scene.setRoot(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The code above generates the following result.
The following code uses the default constructor to create a Hyperlink object. Then it set the a URL as the text caption and finally add click event handler for it.
Hyperlink link = new Hyperlink(); link.setText("http://java2s.com"); link.setOnAction((ActionEvent e) -> { System.out.println("This link is clicked"); });
The setText instance method defines the text caption for the hyperlink.
Hyperlink class extends the Labeled class, and we can set a font and fill for the hyperlink.
The following code adds image to a Hyperlink control.
Hyperlink hpl = new Hyperlink("java2s.com"); Image image1 = new Image(new File("a.jpg").toURI().toString(), 0, 100, false, false); hpl.setGraphic(new ImageView (image1));
Change font for Hyperlink
import java.io.File; //from w w w. jav a 2 s. c om import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage stage) { stage.setTitle("HTML"); stage.setWidth(500); stage.setHeight(500); Scene scene = new Scene(new Group()); VBox root = new VBox(); Hyperlink hpl = new Hyperlink("java2s.com"); hpl.setFont(Font.font("Arial", 14)); root.getChildren().addAll(hpl); scene.setRoot(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The code above generates the following result.