有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在javafx中注册鼠标处理程序,但处理程序不是内联的

我有一个JavaFX中的应用程序,它变得有点大,我想让代码保持可读性

我有一个折线图,我想有放大功能内置,发生在鼠标点击。我知道我需要在图表中注册鼠标侦听器。我无法从Oracle示例中了解到的内容(如本文所述):

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

是如何不让我的处理程序内联定义到注册。换句话说,我希望处理程序的主体(有许多行代码)位于另一个类中。我可以这样做吗?如果是这样,我如何在我的主Javafx控制器代码中将处理程序注册到我的图表中


共 (1) 个答案

  1. # 1 楼答案

    将处理程序放置在一个新类中,该类实现鼠标事件处理程序,并通过节点的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;
            }
          }
        }
      }
    }
    

    Sample program output