Documentation

The Java™ Tutorials
Hide TOC
How to Use Password Fields如何使用密码字段
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Password Fields如何使用密码字段

The JPasswordField class, a subclass of JTextField, provides specialized text fields for password entry. JPasswordField类是JTextField的子类,为密码输入提供专门的文本字段。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.与普通文本字段一样,密码字段在用户指示文本输入完成时(例如,通过按下Enter按钮)触发动作事件

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). 单击启动按钮,使用Java™Web启动运行PasswordDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the PasswordDemo Application

The password is "bugaboo". 密码是“bugaboo”。The password "bugaboo" is an example only. Use secure authentication methods in production systems. 密码“bugaboo”只是一个例子。在生产系统中使用安全身份验证方法。You can find the entire code for this program in PasswordDemo.java. 您可以在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. 传递到JPasswordField构造函数中的参数表示字段的首选大小,在本例中至少为10列宽。By default a password field displays a dot for each character typed. 默认情况下,密码字段为键入的每个字符显示一个点。If you want to change the echo character, call the setEchoChar method. 如果要更改echo字符,请调用setEchoChar方法。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:下面是动作监听器的actionPerformed方法的实现:

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. 为了进一步增强安全性,一旦完成了getPassword方法返回的字符数组,就应该将其每个元素设置为零。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. 该程序调用一个私有方法isPasswordCorrect,将getPassword方法返回的值与存储在字符数组中的值进行比较。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密码字段API

The following tables list the commonly used JPasswordField constructors and methods. 下表列出了常用的JPasswordField构造函数和方法。For information on the API that password fields inherit, see How to Use Text Fields.有关密码字段继承的API的信息,请参阅如何使用文本字段

Commonly Used JPasswordField Constructors and Methods常用的JPasswordField构造函数和方法
Constructor or Method构造函数或方法 Purpose目的
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. 如果存在,int参数指定所需的列宽度。The String argument contains the field's initial text. String参数包含字段的初始文本。The Document argument provides a custom model for the field.Document参数为字段提供了自定义模型。
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)(在JTextField中定义)
Adds or removes an action listener.添加或删除操作侦听器。
void selectAll()
(defined in JTextComponent)
Selects all characters in the password field.选择密码字段中的所有字符。

Examples That Use Password Fields使用密码字段的示例

PasswordDemo is the Tutorial's only example that uses a JPasswordField object. 是本教程中唯一使用JPasswordField对象的示例。However, the Tutorial has many examples that use JTextField objects, whose API is inherited by JPasswordField. 但是,本教程中有许多使用JTextField对象的示例,其API由JPasswordField继承。See Examples That Use Text Fields for further information.有关详细信息,请参阅使用文本字段的示例

If you are programming in JavaFX, see Password Fields.如果您使用JavaFX编程,请参阅密码字段


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