Search code examples
javamouseeventjfreechartcoordinate-systems

JFreeChart interactive chart editing: transforming mouse coordinates into series values


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

XYLineChart

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:

  1. How to calculate exactly the gap in pixel between the last displayed x value and the whole grey chart ? ( big blue line length)
  2. Am I doing something wrong? Is there any simpler way to achieve this goals, possibly avoiding all this calculus? I'm a JFreeChart newbie and the documentation of that library isn't enough, so maybe I'm missing some features that could help me.

Solution

  •   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.