Display ToolTip on PieChart

2019-09-02 21:19发布

问题:

I want to display Tooltip when I move mouse pointer on PieChart. I tested this code:

private ObservableList<Data> pieChartdData = FXCollections.observableArrayList();
    private PieChart chart = new PieChart(pieChartdData);

    public void pieChart(List<FSPartitions> obj)
    {
        for (FSPartitions obj1 : obj)
        {
            String fsName = obj1.getFSName();
            double usedSize = obj1.getUsedSize();

            for (Data d : pieChartdData)
            {
                if (d.getName().equals(fsName))
                {
                    d.setPieValue(usedSize);
                    return;
                }
            }
        }

        for (FSPartitions obj1 : obj)
        {
            String fsName = obj1.getFSName();
            double usedSize = obj1.getUsedSize();

            pieChartdData.add(new Data(fsName, usedSize));
        }

        Platform.runLater(() ->
        {
            final Label captioln = new Label("");
            captioln.setTextFill(Color.DARKORANGE);
            captioln.setStyle("-fx-font: 24 arial;");

            chart.getData().stream().forEach((data) ->
            {
                data.getNode().addEventHandler(MouseEvent.MOUSE_ENTERED,
                    new EventHandler<MouseEvent>()
                    {
                        @Override
                        public void handle(MouseEvent e)
                        {
                            captioln.setTranslateX(e.getSceneX());
                            captioln.setTranslateY(e.getSceneY());
                            captioln.setText(String.valueOf(data.getPieValue()) + "%");
                        }
                    });
            });
        });

        chart.setData(pieChartdData);
    }

I added even Platform.runLater(() to test is this a bug in JavaFX 8u40 but still there is no ToolTip when I move the mouse over the PieChart. This code is executed in JavaFX Task so maybe there is a known issue. Do you have some idea?

回答1:

Try to install tooltip in every node:

chart.getData().stream().forEach(data -> {
    Tooltip tooltip = new Tooltip();
    tooltip.setText(data.getPieValue() + "%");
    Tooltip.install(data.getNode(), tooltip);
    data.pieValueProperty().addListener((observable, oldValue, newValue) -> 
        tooltip.setText(newValue + "%"));
});