How to get mouse position in chart-space

家住魔仙堡 提交于 2019-12-24 05:25:55

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28562195/how-to-get-mouse-position-in-chart-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!