简体   繁体   中英

How to convert ChartPanel Coordinates to XYPlot coordinates in JFreeChart

I have ChartPanel with all Listners implemented on it. On mouse dragging event I am changing the coordinates on my Annotation to redraw as to show dragging action. It is working alright but the coordinates are little messed up. Actually the coordinated I am getting are in context with ChartPanel which are then converting to XYPlots's Axes values therefor the Annotation is drawing at Strange location.

You need to convert the MouseEvent XY coordinates into chart coordinates using java2DToValue() .

ChartPanel mouse handling code

Rectangle2D dataArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
XYPlot xyPlot = chartPanel.getChart().getXYPlot();
// event is the MouseEvent from one of the MouseEvent functions
// store the location and use it later to place the annotation
java.awt.Point clickLocation = new Point(event.getX(), event.getY()); 

Annotation code

double x = xyPlot.getDomainAxis().java2DToValue(clickLocation.getX(), dataArea, xyPlot.getDomainAxisEdge());
double y = xyPlot.getRangeAxis().java2DToValue(clickLocation.getY(), dataArea, xyPlot.getRangeAxisEdge());
String text = Double.toString(x) + " " + Double.toString(y);

XYTextAnnotation annotation = new XYTextAnnotation(text, x, y);
plot.addAnnotation(annotation);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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