为JavaFX LineChart添加了鼠标处理程序,但是坐标与X和Y轴的NumberAxis上的值不匹配。代码段如下

NumberAxis yAxis = new NumberAxis();
NumberAxis xAxis = new NumberAxis();
LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setOnMousePressed(mouseHandler);
lineChart.setOnMouseReleased(mouseHandler);
// Add some values to the chart and click the mouse




EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent mouseEvent) {
        System.out.println(xAxis.getValueForDisplay(mouseEvent.getX()) + " " + yAxis.getValueForDisplay(mouseEvent.getY()));
    }
}

最佳答案

您必须添加以下行并将mouseHandler分配给lineChartmouseHandler,而不是直接将chart-plot-background添加到lineChart中。

Node chartBackground = lineChart.lookup(".chart-plot-background");


它运行完美,请通过以下示例!

https://stackoverflow.com/a/16476292/1759128

编辑

chartBackground.setOnMousePressed(new EventHandler<MouseEvent>() {
      @Override public void handle(MouseEvent mouseEvent) {
        cursorCoords.setVisible(true);
        System.out.println("Mouse Pressed at : " + xAxis.getValueForDisplay(mouseEvent.getX()) + " " +
                yAxis.getValueForDisplay(mouseEvent.getY()));
      }
    });




chartBackground.setOnMouseReleased(new EventHandler<MouseEvent>() {
  @Override public void handle(MouseEvent mouseEvent) {
    cursorCoords.setText(
      String.format(
        "(%.2f, %.2f)",
        xAxis.getValueForDisplay(mouseEvent.getX()),
        yAxis.getValueForDisplay(mouseEvent.getY())
      )
    );
    System.out.println("Mouse Released at : " + xAxis.getValueForDisplay(mouseEvent.getX()) + " " +
            yAxis.getValueForDisplay(mouseEvent.getY()));
  }
});

10-02 22:16