2012-09-07 111 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