如何使用密码字段
原文: https://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html
JPasswordField
类是JTextField
的子类,为密码输入提供专门的文本字段。出于安全原因,密码字段不显示用户键入的字符。相反,该字段显示的字符与输入的字符不同,例如星号’*’。作为另一种安全预防措施,密码字段将其值存储为字符数组,而不是字符串。与普通的文本字段一样,当用户指示文本输入完成时,密码字段会触发动作事件,例如按 Enter 按钮。
这是一个演示图片,打开一个小窗口并提示用户输入密码。
单击“启动”按钮以使用 Java™Web Start (下载 JDK 7 或更高版本)运行 PasswordDemo。或者,要自己编译并运行示例,请参考示例索引。
密码是“bugaboo”。密码“bugaboo”仅为示例。在生产系统中使用安全认证方法。您可以在 PasswordDemo.java
中找到该程序的完整代码。以下是创建和设置密码字段的代码:
passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);
传递给JPasswordField
构造器的参数表示字段的首选大小,在这种情况下至少为 10 列宽。默认情况下,密码字段为每个键入的字符显示一个点。如果要更改回音字符,请调用setEchoChar
方法。然后,代码将一个动作监听器添加到密码字段,该字段检查用户键入的值。以下是动作监听器的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. The preceding code snippet shows how to do this.
使用密码字段的程序通常在完成任何需要密码的操作之前验证密码。该程序调用一个私有方法isPasswordCorrect
,它将getPassword
方法返回的值与存储在字符数组中的值进行比较。这是它的代码:
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;
}
下表列出了常用的JPasswordField
构造器和方法。有关密码字段继承的 API 的信息,请参阅如何使用文本字段。
构造器或方法 | 目的 |
---|---|
JPasswordField() |
JPasswordField(String)
JPasswordField(String,int)
JPasswordField(int)
JPasswordField(Document,String,int) | 创建密码字段。如果存在,int
参数指定列中所需的宽度。 String
参数包含字段的初始文本。 Document
参数为字段提供自定义模型。 |
| char [] getPassword() | 以字符数组的形式返回密码。 |
| void setEchoChar(char)
char getEchoChar() | 设置或获取显示的 echo 字符,而不是用户键入的实际字符。 |
| void addActionListener(ActionListener)
void removeActionListener(ActionListener)
(在JTextField
中定义) | 添加或删除动作监听器。 |
| void selectAll()
(在JTextComponent
中定义) | 选择密码字段中的所有字符。 |
PasswordDemo 是 Tutorial 唯一使用JPasswordField
对象的示例。但是,教程中有许多使用JTextField
对象的示例,其 API 由JPasswordField
继承。有关详细信息,请参阅使用文本字段的示例。
如果您使用 JavaFX 进行编程,请参阅密码字段。