How to handle mouse click events in ImageView JavaFX

Overview

In this tutorial, we show you how to make an ImageView Clickable in JavaFX.
mouse click events in ImageView JavaFX




In JavaFx, ImageView doesn't have an onAction property. If you want to respond to mouse clicks, First setPickOnBounds(true);
imageView.setPickOnBounds(true);
and set setOnMouseClicked (EventHandler) to ImageView
imageView.setOnMouseClicked(new EventHandler() {
 @Override
 public void handle(MouseEvent event) {
  Alert a = new Alert(Alert.AlertType.INFORMATION);
  a.setContentText("This is checkmark");
  a.show();
 }
});

Full Source Code

Project Structure

Project Structure

Example.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>


<AnchorPane id="AnchorPane" fx:id="main" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.jackrutorial.ExampleController">
    
</AnchorPane>

ExampleController.java
package com.jackrutorial;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;


public class ExampleController implements Initializable {

    @FXML
    private AnchorPane main;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {

        ImageView imageView = new ImageView(new Image("com/jackrutorial/img/checkmark.png"));
        imageView.setFitWidth(256);
        imageView.setFitHeight(256);

        imageView.setPickOnBounds(true);

        imageView.setOnMouseClicked(new EventHandler() {
            @Override
            public void handle(MouseEvent event) {
                Alert a = new Alert(Alert.AlertType.INFORMATION);
                a.setContentText("This is checkmark");
                a.show();
            }
        });
        
        main.getChildren().add(imageView);

    }

}

JavaExample.java 

package com.jackrutorial;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class JavaExample extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Example.fxml"));
        
        Scene scene = new Scene(root);
        primaryStage.setTitle("JavaFX ImageView OnAction");
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
}
checkmark.png
checkmark
 

Output

screens
screens

Previous Post
Next Post

post written by: