2017-11-04 116 views
0

所以,我創建了2矩形,並檢查他們是否有交叉,但每次都得到不同的結果:了JavaFx Shape相交始終返回false /真

Rectangle a = new Rectangle(10.00, 10.00); 
    Rectangle b = new Rectangle(30.00, 20.00); 

    a.setFill(Color.RED); 
    _centerPane.getChildren().add(a); 
    _centerPane.getChildren().add(b); 

    //both at 0.00 
    System.out.println(a.intersects(b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight())); //true 
    System.out.println(b.intersects(a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight())); //true 

    a.setLayoutX(100.00); 
    a.setLayoutY(100.00); 

    //only a at different position and not visually intersecting 
    System.out.println(a.intersects(b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight())); //true 
    System.out.println(b.intersects(a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight())); //false 

    b.setLayoutX(73.00); 
    b.setLayoutY(100.00); 

    //Now b is set near a and intersects a visually 
    System.out.println(a.intersects(b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight())); //false 
    System.out.println(b.intersects(a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight())); //false 

回答

1

這是因爲你混合layoutXlayoutYxy。如果您運行下面的代碼(我修改原密碼,並增加了一些打印語句),你會看到,雖然你改變layoutXlayoutY當你調用a.intersects(b.getLayoutX(), ...)這是測試如果a這是在(0,0),並有大小(10,10)與在(100,100)一個矩形相交,答案是,當然,沒有。

代替使用setLayoutXgetLayoutX(或Y)只使用setX/getXsetY/getY的。

public static void test(Rectangle a, Rectangle b) { 
    System.out.println(a.intersects(b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight())); 
    System.out.println(b.intersects(a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight())); 
} 

public static void print(String name, Rectangle r) { 
    System.out.println(name + " : " + r.toString() + " layoutX: " + r.getLayoutX() + " layoutY: " + r.getLayoutY()); 
} 

public static void main(String[] args) { 
    Rectangle a = new Rectangle(10.00, 10.00); 
    Rectangle b = new Rectangle(30.00, 20.00); 

    //both at 0.00 
    print("a", a); 
    print("b", b); 
    test(a, b); // true, true 

    a.setLayoutX(100.00); 
    a.setLayoutY(100.00); 

    //only a at different position and not visually intersecting 
    print("a", a); 
    print("b", b); 
    test(a, b); // true, false 

    b.setLayoutX(73.00); 
    b.setLayoutY(100.00); 

    //Now b is set near a and intersects a visually 
    print("a", a); 
    print("b", b); 
    test(a, b); // false, false 
} 
+0

使用setX()代替setLayoutX()爲我工作,但必須在所有設置了位置的地方替換它們,否則相交不起作用。但他們之間的區別是什麼,他們的工作是一樣的。當涉及到用例時,它們相當混亂。 謝謝:) – rafsuntaskin

+0

setX的()改變矩形本身的值。 setLayoutX()從'Node'類繼承並且被設計爲告訴它需要在視覺上的對象。矩形已經知道它需要的位置,但其他對象可能沒有內部的X或Y位置。或者,它可以用來覆蓋Node的關於應該放置在哪裏的想法。無論哪種方式,它都會覆蓋對象的默認位置。 – BinderNews