2012-09-07 56 views
2

我在JavaFX中有一个应用程序有点大,我想保持代码的可读性。注册鼠标处理程序但处理程序不内联,在javafx

我有一个LineChart,我想要内置缩放功能,发生在鼠标点击上。我知道我需要在图表中注册一个鼠标监听器。我无法从Oracle实例弄清楚,即作为这里写的:

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

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

回答

3

将您的处理程序放在一个实现MouseEventHandler的新类中,并通过节点的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

+0

精确。谢谢! – passiflora