2017-11-04 97 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