如何验证在 JavaFX 密码字段中输入的密码?
object oriented programmingprogrammingjavafx更新于 2025/6/26 6:07:17
文本字段接受并显示文本。在最新版本的 JavaFX 中,它只接受单行文本。
与文本字段类似,密码字段也接受文本,但它不显示输入的文本,而是通过显示回显字符串来隐藏输入的字符。
在 JavaFX 中,javafx.scene.control.PasswordField 表示密码字段,它继承自 Text 类。要创建密码字段,您需要实例化该类。
该类从其超类 TextInputControl 继承了一个名为 text 的属性。此属性保存当前密码字段的内容。您可以使用 getText() 方法检索此数据。
示例
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; public class PasswordFieldVerification extends Application { public void start(Stage stage) { //创建节点 TextField textField = new TextField(); PasswordField pwdField = new PasswordField(); Button button = new Button("Submit"); button.setTranslateX(250); button.setTranslateY(75); //创建标签 Label label1 = new Label("Name: "); Label label2 = new Label("密码:"); //使用读取的数据设置消息 Text text = new Text(""); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 10); text.setFont(font); text.setTranslateX(15); text.setTranslateY(125); text.setFill(Color.BROWN); //显示消息 button.setOnAction(e -> { // 获取数据 String name = textField.getText(); String pwd = pwdField.getText(); if(pwd.equals("abc123")) { text.setText("Hello "+name+" Welcome to Tutorialspoint"); } else { text.setText("Wrong password try again"); } }); //为节点添加标签 HBox box = new HBox(5); box.setPadding(new Insets(25, 5 , 5, 50)); box.getChildren().addAll(label1, textField, label2, pwdField); Group root = new Group(box, button, text); //设置舞台 Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Password Field Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出
密码输入:− mypassword
密码输入:− abc123