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