JavaFX: How to correctly implement `getValueForDisplay()` on Y Axis of a XY line Graph?

∥☆過路亽.° 提交于 2019-12-08 10:38:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!