Search code examples
javajavafxchartsscatter

Get coordinates of a scatter chart XYChart.Data JavaFX


I am trying to get coordinates of each data (dot) of a series of a scatter chart.

public class Main extends Application {

@Override public void start(Stage stage) {
    stage.setTitle("Scatter Chart Issue");
    final NumberAxis xAxis = new NumberAxis(0, 10, 1);
    final NumberAxis yAxis = new NumberAxis(-100, 500, 100);
    final ScatterChart<Number,Number> sc = new
            ScatterChart<Number,Number>(xAxis,yAxis);
    xAxis.setLabel("Time");
    yAxis.setLabel("Random data");
    sc.setTitle("Chart");

    XYChart.Series series1 = new XYChart.Series();
    series1.setName("Series1");
    series1.getData().add(new XYChart.Data(4.2, 193.2));
    series1.getData().add(new XYChart.Data(2.8, 33.6));
    series1.getData().add(new XYChart.Data(6.2, 24.8));
    sc.getData().add(series1);


    for(XYChart.Data<Number, Number> dot : sc.getData().get(0).getData()) {
        double xCoordinate = dot.getNode().localToScene(dot.getNode().getBoundsInLocal()).getMinX();
        double yCoordinate = dot.getNode().localToScene(dot.getNode().getBoundsInLocal()).getMinY();
        System.out.println(xCoordinate + ", " + yCoordinate);
    }



    Scene scene  = new Scene(sc, 500, 400);
    stage.setScene(scene);
    stage.show();
}

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

}

Here is what I get, it appears that all dots of the series have the same coordinates, which is false: enter image description here

My question is therefore : how can I get the coordinates of each data from a series of a scatter chart ? Thank you.

Edit : complete working class added


Solution

  • Place the for loop after the stage.show :

    You're asking for the coordinates before layout has occurred (so the coordinates of all the nodes have not been set).

    Scene scene  = new Scene(sc, 500, 400);
    stage.setScene(scene);
    stage.show();
    
    for(XYChart.Data<Number, Number> dot : sc.getData().get(0).getData()) {
        double xCoordinate = dot.getNode().localToScene(dot.getNode().getBoundsInLocal()).getMinX();
        double yCoordinate = dot.getNode().localToScene(dot.getNode().getBoundsInLocal()).getMinY();
        System.out.println(xCoordinate + ", " + yCoordinate);
    }