2

I'm trying to get the x,y of a point on a LineChart<Number, Number> so that I can add a Line onto it. So I tried to get the x-value of 9 for example by doing:

Group root = new Group(); 
NumberAxis xAxis = new NumberAxis();
xAxis.setAutoRanging(false);
xAxis.setLowerBound(0);
xAxis.setUpperBound(9);
LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
System.out.println(xAxis.getDisplayPosition(9)); // 0
root.getChildren().add(lineChart);
Scene scene = new Scene(root, 800, 800); 
stage.setScene(scene);
stage.show();

After looking around on the internet I came across a supposed solution

Node chartPlotArea = lineChart.lookup(".chart-plot-background");
double chartZeroX = chartPlotArea.getLayoutX();
System.out.println(xAxis.getDisplayPosition(9) + chartZeroX);

Which also ended up outputting 0, why does this happen? How can I get the display position of the x,y so that I can pass that into Line.setStartX(...)/Line.setStartY(...)?

newbie
  • 1,551
  • 1
  • 11
  • 21
  • 2
    Probably you need to generate a layout pass first, see https://stackoverflow.com/questions/26152642/get-the-height-of-a-node-in-javafx-generate-a-layout-pass – fabian Dec 12 '18 at 01:15

2 Answers2

2

If its not critical - you dont need to generate layout pass programatically here, you can let javaFX calculate it and update just after showing you stage. Just move you logic after stage.show();

and you will have correct output

  stage.show();

  System.out.println(xAxis.getDisplayPosition(9)); 

i`ve got: 443.0

Alex G.
  • 436
  • 4
  • 10
0

As @Alex G. mentioned I had to call getDisplayPosition() after show had been called on the stage. However, this doesn't consider the offset of the graph. Therefore, I had to use Bounds like so:

stage.show();
Node chartArea = lineChart.lookup(".chart-plot-background");
Bounds chartAreaBounds = chartArea.localToScene(chartArea.getBoundsInLocal());
int xOffset = chartAreaBounds.getMinX();
System.out.println(xAxis.getDisplayPosition(9) + xOffset); // 324.21428571428567
newbie
  • 1,551
  • 1
  • 11
  • 21