笔记记录

编写人:老王
时间:2023-04-10
地点:广州


Hyperlink就是一个链接组件

点击不会发生跳转,要实现跳转功能要自己写一个监听事件才行。

  1. package com.example.demo2;
  2. import javafx.application.Application;
  3. import javafx.scene.Scene;
  4. import javafx.scene.control.Button;
  5. import javafx.scene.control.Hyperlink;
  6. import javafx.scene.layout.AnchorPane;
  7. import javafx.scene.layout.HBox;
  8. import javafx.stage.Stage;
  9. public class Main4 extends Application {
  10. public static void main(String[] args) {
  11. launch(args);
  12. }
  13. @Override
  14. public void start(Stage stage) throws Exception {
  15. Button button = new Button("网址按钮");
  16. stage.setHeight(400);
  17. stage.setWidth(800);
  18. Hyperlink hyperlink = new Hyperlink("www.baidu.com");
  19. HBox a1 = new HBox();
  20. a1.getChildren().addAll(button,hyperlink);
  21. Scene scene = new Scene(a1);
  22. stage.setScene(scene);
  23. stage.show();
  24. }
  25. }

运行效果如下:
图片.png无论是点击按钮还是链接都无法跳转,要实现这个功能就需要下面这样去操作一下:

  1. package com.example.demo2;
  2. import javafx.application.Application;
  3. import javafx.application.HostServices;
  4. import javafx.event.ActionEvent;
  5. import javafx.event.EventHandler;
  6. import javafx.scene.Scene;
  7. import javafx.scene.control.Button;
  8. import javafx.scene.control.Hyperlink;
  9. import javafx.scene.layout.AnchorPane;
  10. import javafx.scene.layout.HBox;
  11. import javafx.stage.Stage;
  12. public class Main4 extends Application {
  13. public static void main(String[] args) {
  14. launch(args);
  15. }
  16. @Override
  17. public void start(Stage stage) throws Exception {
  18. Button button = new Button("网址按钮");
  19. stage.setHeight(400);
  20. stage.setWidth(800);
  21. Hyperlink hyperlink = new Hyperlink("www.baidu.com");
  22. hyperlink.setOnAction(new EventHandler<ActionEvent>() {
  23. @Override
  24. public void handle(ActionEvent actionEvent) {
  25. HostServices host = getHostServices();
  26. host.showDocument(hyperlink.getText());
  27. }
  28. });
  29. HBox a1 = new HBox();
  30. a1.getChildren().addAll(button,hyperlink);
  31. Scene scene = new Scene(a1);
  32. stage.setScene(scene);
  33. stage.show();
  34. }
  35. }

此时点击链接处就能自动跳转到百度。图片.png也可以用Hyperlink的一个类方法,直接添加一个组件,点击组件就可以打开网页的形式。如下:
图片.png