Hyperlink类表示类似于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;public class Main extends Application {@Overridepublic 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.baidu.com");root.getChildren().addAll(link);scene.setRoot(root);stage.setScene(scene);stage.show();}public static void main(String[] args) {launch(args);}}

package com.javafx05;import java.awt.Desktop;import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.ScrollPane;import javafx.scene.layout.AnchorPane;import javafx.scene.web.WebView;public class JavaFx11 extends Application {@Overridepublic void start(Stage primaryStage) {try {String mInitUrl = "https://www.baidu.com";AnchorPane root = new AnchorPane();Scene scene = new Scene(root);WebView mWebView = new WebView();mWebView.getEngine().load(mInitUrl);mWebView.getEngine().locationProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {Desktop d = Desktop.getDesktop();URI address;try {if(!observable.getValue().contentEquals(mInitUrl)){address = new URI(observable.getValue());d.browse(address);}} catch (URISyntaxException | IOException e) {e.printStackTrace();}}});root.getChildren().add(mWebView);primaryStage.setScene(scene);primaryStage.show();} catch(Exception e) {e.printStackTrace();}}public static void main(String[] args) {launch(args);}}
创建超链接
以下代码使用默认构造函数创建超链接对象。然后它设置一个URL作为文本标题,最后添加点击事件处理程序。
Hyperlink link = new Hyperlink();link.setText("http://www.baidu.com");link.setOnAction(e -> System.out.println("This link is clicked"));
示例
更改超链接的字体,如下代码所示 -
import java.io.File;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 {@Overridepublic 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("www.baidu.com");hpl.setFont(Font.font("Arial", 50));root.getChildren().addAll(hpl);scene.setRoot(root);stage.setScene(scene);stage.show();}public static void main(String[] args) {launch(args);}}

