问题
I am trying to implement tooltip on a line graph to show values of X and Y Axis, i am getting values at X axis correctly, but Y axis values are not getting calculated properly. I tried to do the Math, but nothing helped so far values get incorrect when we resize the window. Is there any logic which help us to calculate value on Y axis correctly?
// lineChart is an object of AreaChart Or XYChart
lineChart.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
Tooltip t= new Tooltip("X:"+lineChart.getXAxis().getValueForDisplay(event.getX()-lineChart.getXAxis().getLayoutX())+", Y:"+
lineChart.getYAxis().getValueForDisplay(event.getY()));
t.show(stage);
}
});
回答1:
This should do what you need:
public void handle(MouseEvent event) {
Point2D pointInScene = new Point2D(event.getSceneX(), event.getSceneY());
Axis<Number> xAxis = lineChart.getXAxis();
Axis<Number> yAxis = lineChart.getYAxis();
double xPosInAxis = xAxis.sceneToLocal(new Point2D(pointInScene.getX(), 0)).getX();
double yPosInAxis = yAxis.sceneToLocal(new Point2D(0, pointInScene.getY())).getY();
double x = xAxis.getValueForDisplay(xPosInAxis).doubleValue();
double y = yAxis.getValueForDisplay(yPosInAxis).doubleValue();
Tooltip t = new Tooltip("X: "+x+", Y:"+y);
t.show(stage);
}
来源:https://stackoverflow.com/questions/31375922/javafx-how-to-correctly-implement-getvaluefordisplay-on-y-axis-of-a-xy-line