score:1

I think the tutorial has dropped some code because we can't show JavaFX controls such as Label without adding it to a javafx.​scene.Parent and the code didn't add it so how it can be shown!!

Here's the same code where we added the Label to a Tooltip and show the Tooltip itself which contains the Label

final Label caption = new Label("");
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");
Tooltip container = new Tooltip();
container.setGraphic(caption);

for (final PieChart.Data data : chart.getData())
{
 data.getNode().addEventHandler(MouseEvent.MOUSE_ENTERED,
         new EventHandler<MouseEvent>()
            {
              @Override
              public void handle(MouseEvent e)
              {
                if (container.isShowing())
                {
                    container.hide();
                }
                caption.setText(String.valueOf(data.getPieValue()) + "%");
                container.show(stage, e.getScreenX(), e.getScreenY());
            }
        });
    }

It's preferred to use Java 8 Lambda Expressions and Streams so the code will be

final Label caption = new Label("");
    caption.setTextFill(Color.DARKORANGE);
    caption.setStyle("-fx-font: 24 arial;");
    Tooltip container = new Tooltip();
    container.setGraphic(caption);

    chart.getData().forEach((data) ->
    {
        data.getNode().
                addEventHandler(MouseEvent.MOUSE_ENTERED, e ->
                {
                    if (container.isShowing())
                    {
                        container.hide();
                    }
                    caption.setText(String.valueOf(data.getPieValue()) + "%");
                    container.show(stage, e.getScreenX(), e.getScreenY());
                });
    });

Hope this is useful


Related Query

More Query from same tag