如何获取鼠标在图表中的位置-space
How to get mouse position in chart-space
如何在图表-space 坐标中获取 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)
);
});
如何在图表-space 坐标中获取 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)
);
});