如何在图表空间中获取鼠标位置

如何在图表空间中获取鼠标位置

本文介绍了如何在图表空间中获取鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如何在图表空间坐标中获取 XYChart< Number,Number> 上的鼠标位置?

How can one obtain the mouse position on an XYChart<Number,Number>, in chart-space coordinates?

以下是我尝试使用 NumberAxis.getValueForDisplay()的示例:

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);
}

}

但是当我运行这个坐标时我得到一个大约10.6,-4.8的偏移误差。

but when I run this the coordinates I get have an offset error of about 10.6, -4.8.

推荐答案

你提供 x y 相对于图表的坐标到 getValueForDisplay(...)方法。您需要相对于实际轴的坐标。 ( xAxis 将从图表的边缘偏移,以允许 yAxis 的水平空间,以及可能的其他填充反之亦然。)

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)
    );
});

这篇关于如何在图表空间中获取鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:13