原文地址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
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
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
Description of "Figure 9-3 Password is Incorrect"
如果输入值符合要求,确认信息就显示出来,见Figure 9-4 .
Figure 9-4 Password is Correct
Description of "Figure 9-4 Password is Correct"
出于安全考虑,最佳实践是键入文本后清空密码框。在Example 9-2 中,身份验证后会将密码框置空 。
?