juung666
juung666

Reputation: 825

How to get the width of the tick label of a LineChart in JavaFx?

How do I get the width of the section highlighted by the red enclosure in the screenshot below?

chart

I have tried

LineChart<Number, Number> sourceChart = ...;
NumberAxis axis = (NumberAxis) sourceChart.getXAxis();
FilteredList<Node> filtered = axis.getChildrenUnmodifiable().filtered(node -> node instanceof Text);
node = filtered.get(0);

filtered is a list of the ticks but node does not have any method that returns the width of the tick like getPrefWidth() or any of that sort.

Upvotes: 1

Views: 482

Answers (2)

juung666
juung666

Reputation: 825

Alright so I figured it out, with the help of JKostikiadis. Basically, as s/he mentioned, you get the layoutX of the plot area, and then just add the plot area's left padding.

Region plotArea = (Region) sourceChart.lookup("Region");
double plotAreaLayoutX = plotArea.getLayoutX();
double chartLeftPad = sourceChart.getPadding().getLeft();
double labelWidth = plotAreaLayoutX + chartLeftPad;

Upvotes: 2

JKostikiadis
JKostikiadis

Reputation: 2917

In most cases the yAxis.getWidth() is more that enough but if you want to be precise there isn't a direct way to get that info (if I am not mistake) so you will have to find a workaround, I would suggest to access the chart-plot-background and then find the layoutX of that Region which is actually the width of your marked area. Here is how you can achieve that :

Region r = (Region) lineChart.lookup("Region"); // access chart-plot-background
double yAxisWidth = r.getLayoutX(); // find out where it starts
System.out.println(yAxisWidth);

To explain the thought here is a picture ( the chart-plot-background has black background color ) :

enter image description here

PS. Still I am not sure that this is the correct approach and it might fail depending on the different CSS rules you may apply on the chart

Upvotes: 0

Related Questions