Mouse EventHandler を実装する新しいクラスにハンドラーを配置し、ノードの setOnClicked メソッドを介してクラスのインスタンスをターゲット ノードに登録します。
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;
}
}
}
}
}