Place the handler in a new class that implements Mouse EventHandler and registers an instance of your class with the target node using the node setOnClicked method.
import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.*; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class ClickHandlerSample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(final Stage stage) throws Exception { stage.setTitle("Left click to zoom in, right click to zoom out"); ImageView imageView = new ImageView("http://upload.wikimedia.org/wikipedia/commons/b/b7/Idylls_of_the_King_3.jpg"); imageView.setPreserveRatio(true); imageView.setFitWidth(150); imageView.setOnMouseClicked(new ClickToZoomHandler()); final StackPane layout = new StackPane(); layout.getChildren().addAll(imageView); layout.setStyle("-fx-background-color: cornsilk;"); stage.setScene(new Scene(layout, 400, 500)); stage.show(); } private static class ClickToZoomHandler implements EventHandler<MouseEvent> { @Override public void handle(final MouseEvent event) { if (event.getSource() instanceof Node) { final Node n = (Node) event.getSource(); switch (event.getButton()) { case PRIMARY: n.setScaleX(n.getScaleX()*1.1); n.setScaleY(n.getScaleY()*1.1); break; case SECONDARY: n.setScaleX(n.getScaleX()/1.1); n.setScaleY(n.getScaleY()/1.1); break; } } } } }

source share