How to show a title for image when I hover over it in JavaFx

5k Views Asked by At

I am doing a project via JavaFx and I have an image and I want to display some information about that image when I hover above it (like the title tag in html).

Any idea how can I do that ?

2

There are 2 best solutions below

0
On BEST ANSWER

Use Tooltip (Tooltip.install()).

Tooltip.install(myImageView, new Tooltip("This is my image."));
3
On

The functionality you're looking for is implemented in the Tooltip class and you can add one to a ImageView using Tooltip.install:

@Override
public void start(Stage primaryStage) {
    Tooltip tooltip = new Tooltip("stackoverflow logo");
    ImageView imageView = new ImageView("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a");
    imageView.setPickOnBounds(true);
    Tooltip.install(imageView, tooltip);

    StackPane root = new StackPane(imageView);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

You can easily write a utility class that allows you to install the Tooltip from an fxml file:

package fxml;

import javafx.scene.Node;
import javafx.scene.control.Tooltip;

public final class TooltipUtil {

    private TooltipUtil() {}

    public static void setTooltip(Node node, Tooltip tooltip) {
        Tooltip.install(node, tooltip);
    }

    // only here for the FXMLLoader
    @Deprecated
    public static Tooltip getTooltip(Node node) {
        throw new UnsupportedOperationException();
    }

}
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Tooltip?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.StackPane?>
<?import fxml.TooltipUtil?>

<StackPane xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ImageView pickOnBounds="true" >
            <image>
                <Image url="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a"/>
            </image>
            <TooltipUtil.tooltip>
                <Tooltip text="stackoverflow logo" />
            </TooltipUtil.tooltip>
        </ImageView>
    </children>
</StackPane>