工具提示是UI元素,使用它可以在GUI应用程序中提供有关元素的其他信息。
每当您将鼠标指针悬停在应用程序中的元素(例如,按钮,标签等)上时,工具提示都会显示有关该元素的提示。
在JavaFX中,工具提示由javafx.scene.control.Tooltip类表示,您可以通过实例化工具提示来创建它。
此类的text属性保存当前工具提示要显示的文本/提示。您可以使用setText()方法将值设置为此属性。或者,您可以仅将要显示的文本(字符串)作为参数传递给工具提示类的构造函数。
创建工具提示后,可以使用install()方法将其安装在任何节点上。(参数-节点和工具提示)。
您还可以使用javafx.scene.control.Control类(所有用户界面控件的父类)的setTooltip()方法将控件提示设置为控件元素。
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) {
//创建标签
Label label1 = new Label("User Name: ");
Label label2 = new Label("Password: ");
//创建文本和密码字段
TextField textField = new TextField();
PasswordField pwdField = new PasswordField();
//为文本字段创建工具提示
Tooltip toolTipTxt = new Tooltip("Enter your user name");
//将工具提示设置为文本字段
Tooltip.install(textField, toolTipTxt);
//创建密码字段的工具提示
Tooltip toolTipPwd = new Tooltip("Enter your password");
//将工具提示设置为文本字段
Tooltip.install(pwdField, toolTipPwd);
//为节点添加标签
HBox box = new HBox(5);
box.setPadding(new Insets(25, 5 , 5, 50));
box.getChildren().addAll(label1, textField, label2, pwdField);
//设置舞台
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);
}
}输出结果