文档

Java™ 教程-Java Tutorials 中文版
如何使用密码框
Trail: Creating a GUI With JFC/Swing
Lesson: Using Swing Components
Section: How to Use Various Components

如何使用密码框

The JPasswordField class, a subclass of JTextField, provides specialized text fields for password entry. For security reasons, a password field does not show the characters that the user types. Instead, the field displays a character different from the one typed, such as an asterisk '*'. As another security precaution, a password field stores its value as an array of characters, rather than as a string. Like an ordinary text field, a password field fires an action event when the user indicates that text entry is complete, for example by pressing the Enter button.

Here is a picture of a demo that opens a small window and prompts the user to type in a password.

A snapshot of PasswordDemo, which uses a password field

Click the Launch button to run PasswordDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

Launches the PasswordDemo Application

The password is "bugaboo". The password "bugaboo" is an example only. Use secure authentication methods in production systems. You can find the entire code for this program in PasswordDemo.java. Here is the code that creates and sets up the password field:

passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);

The argument passed into the JPasswordField constructor indicates the preferred size of the field, which is at least 10 columns wide in this case. By default a password field displays a dot for each character typed. If you want to change the echo character, call the setEchoChar method. The code then adds an action listener to the password field, which checks the value typed in by the user. Here is the implementation of the action listener's actionPerformed method:

public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();

    if (OK.equals(cmd)) { //Process the password.
        char[] input = passwordField.getPassword();
        if (isPasswordCorrect(input)) {
            JOptionPane.showMessageDialog(controllingFrame,
                "Success! You typed the right password.");
        } else {
            JOptionPane.showMessageDialog(controllingFrame,
                "Invalid password. Try again.",
                "Error Message",
                JOptionPane.ERROR_MESSAGE);
        }

        //Zero out the possible password, for security.
        Arrays.fill(input, '0');

        passwordField.selectAll();
        resetFocus();
    } else ...//handle the Help button...
}

Security note: To further enhance security, once you are finished with the character array returned by the getPassword method, you should set each of its elements to zero. The preceding code snippet shows how to do this.

A program that uses a password field typically validates the password before completing any actions that require the password. This program calls a private method, isPasswordCorrect, that compares the value returned by the getPassword method to a value stored in a character array. Here is its code:

private static boolean isPasswordCorrect(char[] input) {
    boolean isCorrect = true;
    char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };

    if (input.length != correctPassword.length) {
        isCorrect = false;
    } else {
        isCorrect = Arrays.equals (input, correctPassword);
    }

    //Zero out the password.
    Arrays.fill(correctPassword,'0');

    return isCorrect;
}

The Password Field API

The following tables list the commonly used JPasswordField constructors and methods. For information on the API that password fields inherit, see How to Use Text Fields.

Commonly Used JPasswordField Constructors and Methods
Constructor or Method 目的
JPasswordField()
JPasswordField(String)
JPasswordField(String, int)
JPasswordField(int)
JPasswordField(Document, String, int)
Creates a password field. When present, the int argument specifies the desired width in columns. The String argument contains the field's initial text. The Document argument provides a custom model for the field.
char[] getPassword() Returns the password as an array of characters.
void setEchoChar(char)
char getEchoChar()
Sets or gets the echo character which is displayed instead of the actual characters typed by the user.
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
(defined in JTextField)
Adds or removes an action listener.
void selectAll()
(defined in JTextComponent)
Selects all characters in the password field.

Examples That Use Password Fields

PasswordDemois the Tutorial's only example that uses a JPasswordField object. However, the Tutorial has many examples that use JTextField objects, whose API is inherited by JPasswordField. See Examples That Use Text Fields for further information.

If you are programming in JavaFX, see Password Fields.


Previous page: How to Use Panels
Next page: How to Use Progress Bars