Tooltip on Live LineChart

前端 未结 3 1152
情书的邮戳
情书的邮戳 2020-12-20 05:57

I found many examples how to add Tooltip on a LineChart but no information or example how to add Tooltip on Live LineChart.

import java.util.concurrent.Concu         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 05:57

    First, use a regular AreaChart instead of the anonymous subclass you are using (i.e. don't override the dataAddedItem(...) method). That method creates a default node to display for the data point if none already exists (this is a huge violation of separating data from presentation, imho, but there's nothing we can do about that...); you obviously need a graphic there to attach the tooltip to.

    Once the data point has a node, you don't need to listen to the changes, so in your addDataToSeries() method, remove the listener and just replace it with

            Tooltip t = new Tooltip(data.getYValue().toString() + '\n' + data.getXValue());
            Tooltip.install(data.getNode(), t);
    

    Or, just create your own graphic, attach a tooltip to it, and pass it to data.setNode(...);.

    You will still have a general usability problem; I don't see how the user is going to hover over a data point in the chart when everything is flying by at 5 units per second. And even if they could, by the time the tooltip appeared the points would have moved, so the values would be incorrect...

    Update:

    Just for fun, I tried this:

        ObjectProperty mouseLocationInScene = new SimpleObjectProperty<>();
    
        Tooltip tooltip = new Tooltip();
    
        sc.addEventHandler(MouseEvent.MOUSE_MOVED, evt -> {
            if (! tooltip.isShowing()) {
                mouseLocationInScene.set(new Point2D(evt.getSceneX(), evt.getSceneY()));
            }
        });
    
        tooltip.textProperty().bind(Bindings.createStringBinding(() -> {
            if (mouseLocationInScene.isNull().get()) {
                return "" ;
            }
            double xInXAxis = xAxis.sceneToLocal(mouseLocationInScene.get()).getX() ;
            double x = xAxis.getValueForDisplay(xInXAxis).doubleValue();
            double yInYAxis = yAxis.sceneToLocal(mouseLocationInScene.get()).getY() ;
            double y = yAxis.getValueForDisplay(yInYAxis).doubleValue() ;
            return String.format("[%.3f, %.3f]", x, y);
        }, mouseLocationInScene, xAxis.lowerBoundProperty(), xAxis.upperBoundProperty(),
        yAxis.lowerBoundProperty(), yAxis.upperBoundProperty()));
    
        Tooltip.install(sc, tooltip);
    

    This sets a tooltip on the chart that updates both as you move the mouse and as the chart scrolls below. This combines ideas from this question and this one.

提交回复
热议问题