我想通过鼠标点击在我的应用程序中设置点。我使用 JFreeChart 并在 ChartPanel 鼠标监听器中使用。这看起来像这样:
panel.addChartMouseListener(new ThisMouseListener());
和我的鼠标监听器 ThisMouseListener()(尚未完成):
class ThisMouseListener implements ChartMouseListener{
@Override
public void chartMouseClicked(ChartMouseEvent event) {
int x = event.getTrigger().getX();
int y = event.getTrigger().getY();
System.out.println("X :" + x + " Y : " + y);
ChartEntity entity = event.getEntity();
if(entity != null && (entity instanceof XYItemEntity)){
XYItemEntity item = (XYItemEntity)entity;
}
new JOptionPane().showMessageDialog(null, "Hello", "Mouse Clicked event", JOptionPane.OK_OPTION);
}
@Override
public void chartMouseMoved(ChartMouseEvent arg0) {
// TODO Auto-generated method stub
}
}
但是这个鼠标监听器返回我的面板坐标,我想从我的图表中获取坐标。可能是我必须将监听器与其他对象一起使用吗?或者我可以用某种方法转换坐标?
最佳答案
您已将监听器添加到面板。因此,当您单击鼠标时,您会收到相对于面板的坐标 - 这是事件的来源。您需要将此监听器添加到图表中。
另一种可能性是获取图表相对于面板的坐标,并从 x 和 y 中减去它们。
Point p = chart.getLocation();
int px = p.getX();
int py = p.getY();
x = x-px; // x from event
y = y-py; // y from event
// x and y are now coordinates in respect to the chart
if(x<0 || y<0 || x>chart.getWidth() || y>chart.getHeight()) // the click was outside of the chart
else // the click happened within boundaries of the chart and
如果面板是图表组件的容器,您的解决方案可能类似于上面的解决方案。请注意,这些坐标将是相对于图表左上角的坐标。
关于java - 将鼠标监听器坐标转换为图表坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12626454/