简体   繁体   English

如何在JFreeChart散点图中找到距鼠标最近的点?

[英]How to find the nearest point to the mouse in a JFreeChart scatter plot?

I need to be able to take a point, as returned from a MouseListener, and identify the nearest point in a scatter plot. 我需要能够获取一个从MouseListener返回的点,并标识散点图中的最近点。 I'm using JFreeChart with an XYDataset. 我正在将JFreeChart与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. 我在ChartPanel中添加了一个鼠标侦听器,并试图将这些x,y值与迭代数据并检查其位置时返回的值进行比较。 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. 问题在于MouseEvent报告的是相对于ChartPanel左上角的点,因此(0,0)在标题上方,在x轴标签的左侧。 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. 但是,valueToJava2D方法提供相对于绘制值的区域的值,因此(0,0)在图形标题下方和x轴标签的右侧。 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 谢谢,埃里克

I'd look at a ChartMouseListener , illustrated here and here . 我将看一下这里此处说明的ChartMouseListener

If that is not sufficient, you may have to have to look at the axis, where the area and edge have meaning. 如果这还不够,则可能必须查看轴,该轴的面积和边缘有意义。

It may help to explain the goal, rather than your current approach. 这可能有助于解释目标,而不是您当前的方法。 Alternatively, edit your question to include an sscce that shows your current approach. 或者,编辑您的问题以包括显示您当前方法的sscce Many short examples may be found here . 这里可以找到许多简短的例子。

Addendum: The practical limit on the max # of points is quite small. 附录: 最大点数的实际限制很小。

For a reasonable number of points, you can enlarge the Shape , as shown here and here ; 对于合理数量的点,可以放大Shape ,如此此处所示; see also ShapeUtilities . 另请参见ShapeUtilities To call out details, consider a custom tooltip generator, examined here . 要指出细节,请考虑在此处检查的自定义工具提示生成器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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