I have an XYLineChart built with JFreeChart. I need, given that chart and a ChartMouseEvent, retrieve the X value of the displayde series closest to the point where the mouse has been clicked.
Thanks to a previous post I have been able to retrieve the offset of the grey chart (the coordinates of the green point in the image) and its dimension with the following method:
Rectangle2D greyChartArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
I also know the max X values of the displayed serie:
double maxXValue = seriesCollection.getDomainUpperBound(true); //where seriesCollection is an XYSeriesCollection object
Now the problem is that for converting a mouse coordinate (Point) into a corresponding value in the chart, I need to know at how many units (double) correspond a pixel on the screen. Unfortunately there is a gap between the maximum X value (60 in this case) and the grey chart width (look at the big blue line), so I can't achieve a perfect conversion.
Then I have two questions:
final XYPlot plot = getChart().getXYPlot();
final ValueAxis domainAxis = plot.getDomainAxis();
final ValueAxis rangeAxis = plot.getRangeAxis();
final Rectangle2D plotRectangle = SWTUtils.toAwtRectangle(getScreenDataArea());
final double chartX = domainAxis.java2DToValue(relativeX, plotRectangle, plot.getDomainAxisEdge());
final double chartY = rangeAxis.java2DToValue(relativeY, plotRectangle, plot.getRangeAxisEdge());
We have used this to get the data coordinates from the mouse coordinates.