有没有一种简单的方法可以在JPasswordField
不创建包含密码的 String 对象的情况下填充 a 的文档?
我试图创建一个“更改密码”对话框,该对话框接受旧密码并要求输入两次新密码(三个密码字段),其中旧密码可能事先已知,具体取决于用户如何配置此密码(密码可能已被存储)。因此,我不想在每次向她显示相关对话框时都要求用户输入现有密码,而是想以编程方式填写它。
请注意,JPasswordField.setText(String)
构造String
函数不是一个选项。我想使用char
数组来做到这一点。
我一直在尝试滥用GapContent
似乎被 使用的PlainDocument
,但它似乎不起作用(字符在那里,但该字段已损坏):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.text.PlainDocument;
import javax.swing.SwingUtilities;
import javax.swing.text.GapContent;
public class FillJPasswordField extends JFrame {
private JPasswordField pass;
public FillJPasswordField() {
setLayout(new GridBagLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
PlainDocument doc = new PlainDocument(new MyGapContent(password));
pass = new JPasswordField(doc, null, 20);
// see if the password is in there
System.out.println(new String(pass.getPassword()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
gbc.insets = new Insets(10, 5, 10, 5);
add(pass, gbc);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FillJPasswordField().setVisible(true);
}
});
}
private class MyGapContent extends GapContent {
public MyGapContent() {
super();
}
public MyGapContent(int initialLength) {
super(initialLength);
}
public MyGapContent(char[] content) {
this(content.length);
replace(0, 0, content, content.length);
}
}
}