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