简体   繁体   中英

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?

图表

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.

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;

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 ) :

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM