How to add a tooltip to a node that does not implement Control using FXML?

JavaFX Control subclasses have a tooltip property, which means you can declaratively add a Tooltip using FXML:

<CheckBox fx:id="someCheckBox" mnemonicParsing="false" text="Do It?"> <tooltip> <Tooltip text="Whether or not to do it."/> </tooltip> </CheckBox> 

This is only possible because the CheckBox is a subclass of Control.

However, I would like to be able to add a tooltip to any Node scene chart using FXML (i.e. without having to programmatically add a tooltip using Java).

+5
source share
1 answer

There is an archival discussion on the Oracle community forum that suggests wrapping Node inside a ScrollPane and setting a tooltip on a ScrollPane. This is less than ideal, but since it adds an unnecessary Node to the scene graph, but more importantly, it does not work well in all scenarios. Try adding a tip to the TitledPane chart :

 <TitledPane text="My TitledPane" fx:id="someTitledPane" expanded="true" contentDisplay="RIGHT"> <graphic> <ScrollPane fitToWidth="true" fitToHeight="true" style="-fx-background-color: rgba(255, 255, 255, 0);"> <ImageView fitWidth="24.0" fitHeight="24.0" preserveRatio="true" pickOnBounds="true"> <image> <Image url="/images/questionMark.jpg" /> </image> </ImageView> <tooltip> <Tooltip text="My tooltip."/> </tooltip> </ScrollPane> </graphic> <Label text="Hello!"/> </TitledPane> 

Although ScrollPane has a transparent background, there is still a visible white box on the question mark graph:

ScrollPane leaves a white background - not perfect!

To do this, there is a way that should use the power of <fx:script> :

 <?language javascript?> <TitledPane text="My TitledPane" fx:id="someTitledPane" expanded="true" contentDisplay="RIGHT"> <graphic> <ImageView fx:id="questionMarkImageView" fitWidth="24.0" fitHeight="24.0" preserveRatio="true" pickOnBounds="true"> <image> <Image url="/images/questionMark.jpg" /> </image> </ImageView> <fx:script> var tooltip = new javafx.scene.control.Tooltip('My tooltip'); javafx.scene.control.Tooltip.install(questionMarkImageView, tooltip); </fx:script> </graphic> <Label text="Hello!"/> </TitledPane> 

Please note that the fx:id for ImageView is referenced inside the script (I did not see this function being documented anywhere and found it only through experimentation), which actually prompted me to publish this Q & A in the hope that others would consider it useful). The results look like this:

No white background and even less Node in the graph scene - perfect!

+4
source

All Articles