Reputation: 6959
How can one obtain the mouse position on an XYChart<Number,Number>
, in chart-space coordinates?
Here is an example of my attempt using NumberAxis.getValueForDisplay()
:
public class Test extends Application {
@Override
public void start(Stage primaryStage) {
Axis<Number> xAxis = new NumberAxis();
Axis<Number> yAxis = new NumberAxis();
XYChart<Number,Number> chart = new AreaChart<>(xAxis,yAxis);
Pane root = new AnchorPane();
root.getChildren().add(chart);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
chart.setOnMousePressed((MouseEvent event) -> {
primaryStage.setTitle("" +
xAxis.getValueForDisplay(event.getX()) + ", " +
yAxis.getValueForDisplay(event.getY())
);
});
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
but when I run this the coordinates I get have an offset error of about 10.6, -4.8.
Upvotes: 2
Views: 2121
Reputation: 209358
You are providing the x
and y
coordinates relative to the chart to the getValueForDisplay(...)
methods. You need the coordinates relative to the actual axes. (The xAxis
will be offset from the edge of the chart to allow horizontal room for the yAxis
, and possibly other padding, and vice-versa.)
To do this, get the coordinates of the mouse event relative to the scene and transform them to the coordinate systems of the axes:
chart.setOnMousePressed((MouseEvent event) -> {
Point2D mouseSceneCoords = new Point2D(event.getSceneX(), event.getSceneY());
double x = xAxis.sceneToLocal(mouseSceneCoords).getX();
double y = yAxis.sceneToLocal(mouseSceneCoords).getY();
primaryStage.setTitle("" +
xAxis.getValueForDisplay(x) + ", " +
yAxis.getValueForDisplay(y)
);
});
Upvotes: 4