Search code examples
javajavafxconvex-hull

Is there a way to dynamically draw lines between points over a coordinate plane?


I am completing a project in which I have implemented a brute force algorithm for solving the Convex Hull problem. I need to also create a visual for this algorithm. I am trying to create a coordinate plane ranging from (-100, 100) on both the x and y axis, plot all the points in the complete set, and dynamically draw lines between the points in order to create the convex hull. For example, assume I have 4 points: A(1, 1), B(3,2), C(2, 4), and D(1,3). I want to first plot all four of these points and then draw a line from A to B and then from B to C and then from C to D and then finally from D to A. So far I have been trying to do this using JavaFX LineChart.

//        creating axis
        NumberAxis xAxis = new NumberAxis(-100, 100, 1);
        NumberAxis yAxis = new NumberAxis(-100, 100, 1);
//        creating chart
        LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);

and then drew lines using

   public static void populatePoints(List<Double []> points, LineChart lineChart) {
        XYChart.Series series = new XYChart.Series();
        series.setName("Points of set");
        for (Double[] point : points) {
            series.getData().add(new XYChart.Data<Double, Double>(point[0], point[1]));
        }
        lineChart.getData().add(series);
    }

However, this just draws the lines in a typical line chart fashion. I need it to be in a convex shape. I have attached the result of my current code with points (-51.6, 72.97), (33.58, 98.97), (-86.68, 9.77), and (-49.41, -46.26).After running program with points: (-51.6, 72.97), (33.58, 98.97), (-86.68, 9.77), and (-49.41, -46.26)


Solution

  • You can use the approach shown here:

    • Add the points to the series in the desired order.

    • Specify SortingPolicy.NONE.

        series.getData().add(new XYChart.Data(-86.68,  9.77));
        series.getData().add(new XYChart.Data(-51.6,   72.97));
        series.getData().add(new XYChart.Data( 33.58,  98.97));
        series.getData().add(new XYChart.Data(-49.41, -46.26));
        series.getData().add(new XYChart.Data(-86.68,  9.77));
        …
        policy.getSelectionModel().select(LineChart.SortingPolicy.NONE);
      

    hull image