How to set image as hyperlink in JavaFX?


An Hyperlink is a UI component that responds to clicks and roll overs. You can create a hiperlink by instantiating the javafx.scene.control.Hiperlink class. You can set an image as a hiperlink using the setGraphic() method.

Example

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.geometry.Insets;
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.paint.Color;
import javafx.stage.Stage;
public class HyperLinkSettingGraphic extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a hyper link
      Hyperlink link = new Hyperlink();
      //Creating a graphic
      ImageView view = new ImageView();
      InputStream stream = new FileInputStream("D:\images\logo.jpg");
      Image image = new Image(stream);
      view.setImage(image);
      view.setFitHeight(100);
      view.setFitWidth(200);
      //Setting the graphic to the hyperlink
      link.setGraphic(view);
      //Creating a vbox to hold the pagination
      VBox vbox = new VBox();
      vbox.setSpacing(5);
      vbox.setPadding(new Insets(50, 50, 50, 170));
      vbox.getChildren().addAll(link);
      //Setting the stage
      Group root = new Group(vbox);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Hyperlink");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 19-May-2020

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements