-2

I am trying to set a panel that contains several points and then draw a triangle or any others forms. And all points that are inside that form will switch their colors to red.

Seems like i am doing something wrong, is this the correct way to draw point inside the for loop ?

Blaviken25
  • 49
  • 7
  • The `Polygon` and a `Circle` don't interact with one another by default. Why do you expect this to happen? You're filling all the with black color unconditionally and the only relationship between circles and and polygon is that they share the same parent... – fabian Aug 17 '18 at 12:12
  • Can you suggest any other approach ? I just want all the points inside the triangle to switch their color to red. I am new with JavaFX. Thanks – Blaviken25 Aug 17 '18 at 12:27
  • All of the `Circles` intersecting the `Polygon` should be colored red completely or should only the parts of the circles inside the polygons be colored red? – fabian Aug 17 '18 at 12:46
  • BTW: `double x = 65.0f`??? `f` is the suffix for `float`. For `double` it would be `d` and it's not required, if the conversion does not require a cast (`double x = 65` would work even though `65` is an `int`) and floating point values without a suffix are treated as `double` by default. (This is why `triangle.getPoints().addAll(300.0, 100.0, 600.0, 150.0,500.0, 300.0);` works but `triangle.getPoints().addAll(300f, 100f, 600f, 150f, 500f, 300f);` doesn't) – fabian Aug 17 '18 at 12:51
  • Sorry i made a mistake for the double x = 65.0f. I want the circles inside the triangle to be completely colored red and the others ones remain black. – Blaviken25 Aug 17 '18 at 12:54

1 Answers1

1

Make sure the Polygon is created before creating the circles. This allows you to use check for intersection of the shapes as described in this answer: https://stackoverflow.com/a/15014709/2991525

Choose the circle fill accordingly:

@Override
public void start(Stage stage) {
    Group root = new Group();

    Polygon triangle = new Polygon(300d, 100d, 600d, 150d, 500d, 300d);
    root.getChildren().add(triangle);

    Scene scene = new Scene(root, 900, 500);

    for (double x = 65; x < scene.getWidth(); x += 65) {
        for (double y = 65; y < scene.getHeight(); y += 65) {
            Circle circle = new Circle(x, y, 10);

            root.getChildren().add(circle);

            Shape intersection = Shape.intersect(circle, triangle);

            //Setting the color of the circle
            circle.setFill(intersection.getBoundsInLocal().getWidth() == -1 ? Color.BLACK : Color.RED);
        }
    }

    triangle.setFill(Color.TRANSPARENT);
    triangle.setStroke(Color.RED);
    triangle.toFront();

    stage.setTitle("Scale transition example");
    stage.setScene(scene);
    stage.show();
}
fabian
  • 80,457
  • 12
  • 86
  • 114