I need to be able to take a point, as returned from a MouseListener, and identify the nearest point in a scatter plot. I'm using JFreeChart with an XYDataset.
I have added a mouse listener to my ChartPanel, and am trying to compare these x,y values to those returned when I iterate through the data and check their locations. My code looks something like this:
ValueAxis domainAxis = chartPanel.getXYPlot().getDomainAxis();
ChartArea chartArea = chartPanel.getChartRenderingInfo().getChartArea();
for(int i=0; i < myXYData.getItemCount(0); i++) {
double mouseX = e.getX(); // e is the MouseEvent
double pointX = domainAxis.valueToJava2D(myXYData.getX(0, i), chartArea, RectangleEdge.BOTTOM);
System.out.println("difference is " + (pointX - mouseX));
}
The problem is that the MouseEvent is reporting points relative to the top-left of the ChartPanel, so (0,0) is above the title, and left of the x-axis labels. The valueToJava2D method, however, is giving values relative to the area where the values are plotted, so (0,0) is below the graph title and to the right of the x-axis labels. This means that I get a non-zero difference when the mouse is directly over one of my data points!
How can I resolve this disparity?
thanks, Eric