如何获取 XYChart<Number,Number>
上的鼠标位置,在图表空间坐标中?
这是我尝试使用 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);
}
}
但是当我运行这个时,我得到的坐标有大约 10.6, -4.8 的偏移误差。
最佳答案
您正在向 getValueForDisplay(...)
方法提供相对于图表的 x
和 y
坐标。您需要相对于实际轴的坐标。 (xAxis
将从图表边缘偏移,以便为 yAxis
以及可能的其他填充留出水平空间,反之亦然。)
为此,获取鼠标事件相对于场景的坐标并将其转换为轴的坐标系:
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)
);
});
关于javafx - 如何获取鼠标在图表空间中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562195/