鼠标事件的 X 和 Y 坐标对于 Java FX 折线图不正确



为 JavaFX 折线图添加了鼠标处理程序,但坐标与 X 轴和 Y 轴的数字轴上的值不匹配。代码片段如下

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添加到lineChart,而是必须添加以下行并将mouseHandler分配给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()));
  }
});

相关内容

  • 没有找到相关文章

最新更新