2014-09-03 106 views
0

一個非常簡單的問題,我希望有一個簡單的答案。JavaFx防止孩子觸發父母的setOnMouseEntered

我有一個複雜的自定義節點來擴展組。

當孩子徘徊時,我該如何防止JavaFx爲本集團發射setOnMouseEntered事件?

setMouseTransparent hackery似乎沒有辦法。

+0

你嘗試過將[pickOnBoundsProperty]超類(http://docs.oracle.com/javafx/2/api/javafx/scene/Node定義。 HTML#pickOnBoundsProperty)?順便說一下,'setMouseTransparent'將設置爲節點*和*其子節點。 – Vertex 2014-09-04 08:57:39

+0

我剛剛嘗試setPickOnBounds(false/true),但不幸的是它沒有幫助。 – user2499946 2014-09-04 13:38:44

回答

0

我做了一個簡單的測試應用和集團沒有獲得鼠標事件:

private static final class Foo extends Group { 
    Foo() { 
     final Rectangle blue = new Rectangle(100, 100, Color.BLUE); 
     blue.setLayoutX(50); 
     blue.setLayoutY(50); 
     blue.setOnMouseEntered(e -> System.out.println("Entered blue")); 

     final Rectangle green = new Rectangle(100, 100, Color.GREEN); 
     green.setLayoutX(250); 
     green.setLayoutY(90); 
     green.setOnMouseEntered(e -> System.out.println("Entered green")); 

     final Rectangle red = new Rectangle(100, 100, Color.RED); 
     red.setLayoutX(100); 
     red.setLayoutY(200); 
     red.setOnMouseEntered(e -> System.out.println("Entered red")); 

     getChildren().addAll(blue, green, red); 
    } 
} 

@Override 
public void start(final Stage primaryStage) throws Exception { 
    final Pane root = new AnchorPane(); 
    final Foo foo = new Foo(); 
    root.getChildren().add(foo); 
    final Scene scene = new Scene(root); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 

public static void main(String[] args) { 
    launch(args); 
} 

Screenshot of Hover Demo

這是因爲鼠標採摘的實現:

Node#contains實施爲

public boolean contains(double localX, double localY) { 
    if (containsBounds(localX, localY)) { 
     return (isPickOnBounds() || impl_computeContains(localX, localY)); 
    } 
    return false; 
} 

impl_computeContains在父這是

protected boolean impl_computeContains(double localX, double localY) { 
    final Point2D tempPt = TempState.getInstance().point; 
    for (int i=0, max=children.size(); i<max; i++) { 
     final Node node = children.get(i); 
     tempPt.x = (float)localX; 
     tempPt.y = (float)localY; 
     try { 
      node.parentToLocal(tempPt); 
     } catch (NoninvertibleTransformException e) { 
      continue; 
     } 
     if (node.contains(tempPt.x, tempPt.y)) { 
      return true; 
     } 
    } 
    return false; 
} 
+0

嗯,我在你的測試案例中沒有看到你爲組本身設置了一個監聽器?你有沒有包括那一點?無論如何感謝您的測試。但是,通過爲組的矩形設置偵聽器,我獲得了我想要的行爲。我的節點基本上是矩形。我不知道我在做什麼令人費解的事情,如果它真的應該失效。 – user2499946 2014-09-04 15:05:37

+0

@ user2499946,你可以在constrcutor中添加'setOnMouseEntered(e - > System.out.println(「Entered group」));'行。即使在該組中設置了聽衆,也不會收到該組的事件。 – Vertex 2014-09-04 16:09:11