JavaFX Hyperlink

This article covers the Hyperlink widget in JavaFX.

Anyone familiar with the internet should know what a Hyperlink is. Simply put, it’s a link from one document to another, activated by clicking on a word or image.

JavaFX’s Hyperlink widget is similar, but not exactly like a traditional hyperlink. The difference is that we can link a JavaFX Hyperlink to any action, such as printing something to screen or calling a function. If you want, you can also use it to link to a web page. It’s sort of like a text based button.

You can import the Hyperlink widget with the following name: javafx.scene.control.Hyperlink.


Creating a Hyperlink

In order to create a fully functioning Hyperlink, we’ve got to to do things.

  1. We need to create a Hyperlink object using the Hyperlink class.
  2. We need to connect our Hyperlink object to an action that will be executed when the link is clicked. (Event handling)

The syntax for creating a Hyperlink object is pretty simple, as shown below.

Hyperlink link = new Hyperlink("I am a Hyperlink!");

Below is the full code for a Hyperlink example complete with an image of the GUI object. The action is set on the Hyperlink through the use of the setOnAction() method.

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.VBox;


public class Tutorial extends Application {
	public static void main(String args[]){          
		 launch(args);     
	} 
		
	@Override     
	public void start(Stage primaryStage) throws Exception { 
		
		VBox layout = new VBox();
		Scene scene = new Scene(layout, 200, 200);	
		
		Hyperlink link = new Hyperlink();
		link.setOnAction(e -> {
				System.out.println("This is a Link");
		});
	
		layout.getChildren().addAll(link);
	
		primaryStage.setTitle("CodersLegacy");
		primaryStage.setScene(scene);	
		primaryStage.show();
    }
}

The output of the above code:

JavaFX Hyperlink image

Other JavaFX Widgets:


This marks the end of the JavaFX Hyperlink article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments