鼠标相对于原点的位置

时间:2012-09-24 11:00:00

标签: charts javafx-2

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

下面的代码获取鼠标光标相对于图表布局原点的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();
}

1 个答案:

答案 0 :(得分:0)

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