0

如何计算鼠标相对于折线图原点的位置?

下面的代码获取鼠标光标相对于图表布局原点的 x 位置。我想知道鼠标相对于笛卡尔原点的位置。

public class Chart extends Application {

    private NumberAxis xAxis;
    private NumberAxis yAxis;
    private LineChart<Number,Number> lineChart;
    private Label cursorPosition;
    private Label xAxisPosition;

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox();

        xAxis = new NumberAxis("Date", 0.f, 100.f, 10.f);
        yAxis = new NumberAxis("Value", 0.f, 100.f, 10.f);
        lineChart = new LineChart<>(xAxis, yAxis);

    Series series = new Series();
    for (int ii = 1; ii <= 100; ii++) {
        series.getData().add(new Data(ii, Math.random()*20.));
    }
    lineChart.getData().add(series);

    lineChart.setOnMouseMoved(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            lineChart.setCursor(Cursor.CROSSHAIR);
            cursorPosition.setText(String.valueOf(event.getX()));
        }
    });

    lineChart.setOnMouseExited(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            lineChart.setCursor(Cursor.DEFAULT);
        }
    });

    cursorPosition = new Label();
    root.getChildren().addAll(lineChart, cursorPosition,);

    Scene scene = new Scene(root, 300, 250);
    primaryStage.setScene(scene);
    primaryStage.show();
}
4

1 回答 1

0

您必须使用图表的轴在显示坐标和笛卡尔(值)坐标之间进行转换。xAxis.getDisplayPosition(0)例如,将为您提供值 0 的 x 坐标。您还可以使用它将当前鼠标位置转换为“值”。

于 2012-09-24T12:20:23.157 回答