如何验证在JavaFX密码字段中输入的密码?
文本字段接受并显示文本。在最新版本的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("Password: ");
//设置带有读取数据的消息
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 Nhooo");
} 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