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