Registering a mouse handler, but the handler is not built-in, in javafx

I have a JavaFX application that is getting a little big and I want the code to be read.

I have a LineChart that I want to have a built-in zoom function that occurs in mouseclick. I know that I need to register a mouse listener on a chart. What I cannot understand from Oracle examples, i.e. Here:

http://docs.oracle.com/javafx/2/events/handlers.htm

is how to NOT have my handler defined inline for registration. In other words, I want the body of the handler (which has many lines of code) to be in another class. I can do it? And if so, how do I register a handler on my diagram in my main Javafx controller code?

+2
source share
1 answer

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; /** * JavaFX sample for registering a click handler defined in a separate class. * http://stackoverflow.com/questions/12326180/registering-mouse-handler-but-handler-not-inline-in-javafx */ 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; } } } } } 

Sample program output

+3
source

Source: https://habr.com/ru/post/1438521/