2

I made a little program to make colored circles if a point is inside a polygon. But for some reason Polygon.contains is only true when the point is on the line of the polygon. Why?

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Testing extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();

        //Set up polygon
        Polygon polygon1 = new Polygon(30.0, 30.0, 100.0, 3.0, 100.0, 130.0, 60.0, 60.0, 3.0, 100.0, 30.0, 30.0);
        polygon1.setFill(null);
        polygon1.setStroke(Color.BLACK);

        //set up circles
        Circle[] circles = new Circle[26];
        int counter = 0;
        for (int x = 0; x < 130; x+=30) {
            for (int y = 0; y < 130; y+=30) {
                circles[counter] = new Circle(x, y, 4);

                //if circle is inside polygon, color it red
                if (polygon1.contains(x, y)) {
                    circles[counter].setFill(Color.RED);
                }

                pane.getChildren().add(circles[counter]);
                counter++;
            }
        }

        pane.getChildren().addAll(polygon1);

        Scene scene = new Scene(pane, 130, 130);
        primaryStage.setTitle("Exercise14_20");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Output: Polygon w/points as circles

I've tried using a Rectangle instead of a Polygon. I've tried having the polygon's points be in an ObservableList. I've tried just printing out whether .contains is true or not.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
JNowata63
  • 21
  • 4

0 Answers0