在PieChart上显示工具提示

时间:2015-03-04 11:40:30

标签: javafx javafx-8

我想在PieChart上移动鼠标指针时显示工具提示。我测试了这段代码:

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);
    }

我添加了甚至Platform.runLater(()来测试这是JavaFX 8u40中的一个错误,但是当我将鼠标移到PieChart上时仍然没有工具提示。这段代码在JavaFX Task中执行所以可能有一个已知的问题你有什么想法吗?

2 个答案:

答案 0 :(得分:2)

尝试在每个节点中安装工具提示:

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 + "%"));
});

答案 1 :(得分:1)

您也可以尝试以下解决方案:

for(PieChart.Data data: pieChart.getData()){
        Tooltip tooltip = new Tooltip(data.getName() + ": " + data.getPieValue() +"%");
        Tooltip.install(data.getNode(), tooltip);
        
        //respond to change in value
        data.pieValueProperty().addListener((observable, oldPieValue, newPieValue)->{
            tooltip.setText(data.getName() + ": " + newPieValue + "%");
        });
    }