Java FX LineChart的MouseEvent X和Y坐标不正确

时间:2014-02-28 13:09:10

标签: java javafx mouseevent linechart

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

1 个答案:

答案 0 :(得分:2)

您必须添加以下行,并将mouseHandler分配给lineChart的{​​{1}},而不是将mouseHandler直接添加到chart-plot-background。 p>

lineChart

完美无缺,请通过以下示例!

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

编辑

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

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