JavaFX Tooltip
Let’s learn about the JavaFX Tooltip and how to use and customize it. Tooltip is a UI element that is typically used to show a piece of additional information for the user.
The Tooltip is shown when it is added to a node and hovered over by the mouse. You can a Tooltip on any node. The Tooltip is under to javafx.scene.control.Tooltip Class. You can simply import javafx.scene.control.Tooltip; in your IDE.
Tooltip Constructor
It creates a Tooltip with an empty string. See the example code below.
Tooltip tooltip = new Tooltip();
The other one creates a Tooltip with a specified text or string. See the example code below.
Tooltip tooltip = new Tooltip(String text);
How to show a Tooltip in JavaFX
To actually show the Tooltip in your JavaFX application. Let us assume that we already have a button in our JavaFX application. So, to show the Tooltip. You can simply use the code below.
Tooltip tooltip = new Tooltip("This is an example of a Tooltip"); button.setTooltip(tooltip);
Basically, we created a tooltip Object and set the tooltip on a button. Now to customize your tooltip is easy. So in this Tooltip customization. We will just simply change the background color and a Tooltip text color. This is just a basic example to help you learn about the basics of Tooltip in JavaFX.
There are three ways that I know to customize the JavaFX Tooltip style.
-
Customizing the JavaFX Tooltip style using the Cascading Style Sheet (CSS). You may change the background color -fx-background-color: white; etc.
-
The second way to customize the JavaFX Tooltip is by using the inline code. For example, tooltip.setStyle(“-fx-background-color: white”);
-
The third one is by using the Scene Builder. You can set the style at the Tooltip properties.
Customize the JavaFX Tooltip
We will customize the JavaFX Tooltip by using the Cascading Style Sheet (CSS). In this example, we will just change the background color and its text color.
.tooltip{ -fx-background-color: white; -fx-text-fill: black; }
That’s how you change its style with the CSS file. To customize your JavaFX Tooltip purely Java, simply go to your IDE and type this line of code in your IDE.
tooltip.setStyle("-fx-background-color: white; -fx-text-fill: black");
The last one that I know is using the Scene Builder. I will provide a screenshot for you to understand what I mean. Kindly see the screenshot below.