(翻译)第十五回 JavaFX2.0 密码框PasswordField

原文地址http://download.oracle.com/javafx/2.0/ui_controls/password-field.htm#CHDIAAAJ

 

 

PasswordField 类实现了一种特定的文本框:用户向其中输入的字符都被隐藏,代之显示的是特殊的回显串。Figure 9-1 是一个带有提示语的密码框。

Figure 9-1 Password Field with a Prompt Message

A password box with the prompt message
Description of "Figure 9-1 Password Field with a Prompt Message" 

创建Password Field

一个入门级的任务是创建一个密码框,见Example 9-1 .

Example 9-1 Creating a Password Field

PasswordField passwordField = new PasswordField();
passwordField.setPromptText("Your password");

由于是用户接口,所以最好给密码框配上一条提示语或者是一个指示标签。和 TextField   类相同,PasswordField类也提供了 setText 方法来设置在应用启动后要在控件中显示的字符串。但是,setText 方法指定的字符串被密码框的回显字符覆盖了。默认地,密码框的回显字符是星号。Figure 9-2 是带有预定义文本的密码框。

Figure 9-2 Password Field with the Set Text

A password box
Description of "Figure 9-2 Password Field with the Set Text" 

密码框中的值也可以用getText 方法获得。您可以在您的应用程序处理这个值,并设置适当的身份验证逻辑。

处理Password的值

花点时间看Example 9-2 中的代码,它实现了一个密码框。

Example 9-2 Implementing the Authentication Logic

final Label message = new Label("");

VBox vb = new VBox();
vb.setPadding(new Insets(10, 0, 0, 10));
vb.setSpacing(10);
HBox hb = new HBox();
hb.setSpacing(10);
hb.setAlignment(Pos.CENTER_LEFT);

Label label = new Label("Password");
final PasswordField pb = new PasswordField();

pb.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        if (!pb.getText().equals("T2f$Ay!")) {
            message.setText("Your password is incorrect!");
            message.setTextFill(Color.rgb(210, 39, 30));
        } else {
            message.setText("Your password has been confirmed");
            message.setTextFill(Color.rgb(21, 117, 84));
        }
        pb.setText(" ");
    }
});

hb.getChildren().addAll(label, pb);
vb.getChildren().addAll(hb, message);

这里通过setOnAction 方法为密码框定义了身份验证逻辑。该方法调用的时间是提交密码后,它新建了一个EventHandler 对象来处理键入的值。如果输入值和要求值不同,相应的信息就以红色显示出来,见Figure 9-3 .

Figure 9-3 Password is Incorrect

The entered password is incorrect
Description of "Figure 9-3 Password is Incorrect" 

如果输入值符合要求,确认信息就显示出来,见Figure 9-4 .

Figure 9-4 Password is Correct

The password is correct
Description of "Figure 9-4 Password is Correct" 

出于安全考虑,最佳实践是键入文本后清空密码框。在Example 9-2 中,身份验证后会将密码框置空 。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值