Password Field in JavaFX

Domains: Java

Password Field

In this chapter, you learn about yet another type of the text control, the password field.

The PasswordField class implements a specialized text field. The characters typed by a user are hidden by displaying an echo string. Figure 9-1 shows a password field with an entered password.

Figure 9-1 Password Field

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

Creating a Password Field

An entry-level task is to create a password field by using the code in Example 9-1.

Example 9-1 Creating a Password Field

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

For your user interface, you can accompany the password field with a prompt message or you can add a notifying label. As with the TextField class, the PasswordField class provides the setText method to render a text string in the control when the application is started. However, the string specified in the setTextmethod is hidden by the echo characters in the password field. By default, the echo character is a dot. Figure 9-2 shows the password field with the predefined text in it.

Figure 9-2 Password Field with the Set Text

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

The value typed in the password field can be obtained through the getText method. You can process this value in your application and set the authentication logic as appropriate.

Evaluating the Password

Take a moment to review in Example 9-2 the implementation of a password field that you can apply in your user interface.

Example 9-2 Implementing the Authentication Logic

final Label message = new Label("");

VBox vb = new VBox();
vb.setPadding(new Insets(10, 0, 0, 10));
HBox hb = new HBox();

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

pb.setOnAction((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));

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

The authentication logic of the password field is defined by using the setOnAction method. This method is called when a password is committed and it processes the typed value. If the typed value is different from the required password, the corresponding message appears in red as shown in Figure 9-3.

Figure 9-3 Password is Incorrect

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

If the typed value satisfies the predefined criteria, the confirmation message appears as shown in Figure 9-4.

Figure 9-4 Password is Correct

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

Similar pages

Page structure