> 如何使用密码字段
JPasswordField类是JTextField
的子类,它提供用于 Importing 密码的专用文本字段。出于安全原因,密码字段不显示用户键入的字符。而是,该字段显示与键入的字符不同的字符,例如星号“ *”。作为另一项安全预防措施,密码字段将其值存储为字符数组而不是字符串。像普通的text field一样,当用户指示文本 Importing 完成(例如,按 Enter 按钮)时,密码字段会触发action event。
这是演示的图片,该演示会打开一个小窗口并提示用户 Importing 密码。
单击启动按钮以使用Java™Web 开始(下载 JDK 7 或更高版本)运行 PasswordDemo。另外,要自己编译和运行示例,请查阅example index。
密码是“ 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:
为了进一步增强安全性,当您完成getPassword
方法返回的字符数组后,应将其每个元素设置为零。前面的代码片段显示了如何执行此操作。
使用密码字段的程序通常会在完成要求密码的任何操作之前先验证密码。该程序调用私有方法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;
}
密码字段 API
下表列出了常用的JPasswordField
构造函数和方法。有关密码字段继承的 API 的信息,请参见如何使用 Literals 栏位。
构造函数或方法 | Purpose |
---|---|
JPasswordField() | |
JPasswordField(String) JPasswordField(String, int) JPasswordField(int) JPasswordField(Document,String,int) | 创建密码字段。如果存在,则int 参数以列为单位指定所需的宽度。 String 参数包含字段的初始文本。 Document 参数为该字段提供了自定义模型。 |
char[] getPassword() | 以字符数组形式返回密码。 |
void setEchoChar(char) char getEchoChar() | 设置或获取显示的回显字符,而不是用户键入的实际字符。 |
void addActionListener(ActionListener) void removeActionListener(ActionListener) (在 JTextField 中定义) | 添加或删除操作侦听器。 |
void selectAll() (在 JTextComponent 中定义) | 选择密码字段中的所有字符。 |
使用密码字段的示例
PasswordDemo是 Tutorial 唯一使用JPasswordField
对象的示例。但是,本教程有许多使用JTextField
对象的示例,这些对象的 API 由JPasswordField
继承。有关更多信息,请参见使用文本字段的示例。
如果您使用 JavaFX 编程,请参见Password Fields。