How to create a tool tip using JavaFX?

JavaFXObject Oriented ProgrammingProgramming

A tooltip is a UI element, using which you can provide additional information about the elements in a GUI application.

Whenever you hover over the mouse pointer over an element (say, button, label, etc..) in your application, the tooltip displays a hint about it.

In JavaFX the tooltip is represented by the javafx.scene.control.Tooltip class, you can create a tooltip by instantiating it.

Creating the Tooltip

The text property of this class holds the text/hint to be displayed by the current tooltip. You can set the value to this property using the setText() method. Or, you can just pass the text to be displayed (String) as a parameter to the constructor of the tooltip class.

Once you have created a tooltip you can install it on any node using the install() method. (parameters − Node and Tooltip).

You can also set a tooltip to a control element using the setTooltip() method of the javafx.scene.control.Control class ( parent class for all user interfaces controls.)

Example

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class TooltipExample extends Application {
   public void start(Stage stage) {
      //Creating labels
      Label label1 = new Label("User Name: ");
      Label label2 = new Label("Password: ");
      //Creating text and password fields
      TextField textField = new TextField();
      PasswordField pwdField = new PasswordField();
      //Creating tool tip for text field
      Tooltip toolTipTxt = new Tooltip("Enter your user name");
      //Setting the tool tip to the text field
      Tooltip.install(textField, toolTipTxt);
      //Creating tool tip for password field
      Tooltip toolTipPwd = new Tooltip("Enter your password");
      //Setting the tool tip to the text field
      Tooltip.install(pwdField, toolTipPwd);
      //Adding labels for nodes
      HBox box = new HBox(5);
      box.setPadding(new Insets(25, 5 , 5, 50));
      box.getChildren().addAll(label1, textField, label2, pwdField);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("Tooltip Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 18-May-2020 10:24:56
Advertisements