如何限制 Java 中 JPasswordField 内部数字的位数?\n
JPasswordField 是JTextField 的子类,在 JPasswordField 中输入的每个字符都可以替换为回显 字符。这允许为密码输入机密信息。JPasswordField 的重要方法是getPassword()、getText()、getAccessibleContext()等。默认情况下,我们可以在 JPasswordField 中输入任意数量的数字。如果我们希望通过实现DocumentFilter 类 来限制用户输入的数字,并且需要覆盖replace() 方法。
语法
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
示例
import java.awt.*; import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class JPasswordFieldDigitLimitTest extends JFrame { private JPasswordField passwordField; private JPanel panel; public JPasswordFieldDigitLimitTest() { panel = new JPanel(); ((FlowLayout) panel.getLayout()).setHgap(2); panel.add(new JLabel("Enter Pin: ")); passwordField = new JPasswordField(4); PlainDocument document = (PlainDocument) passwordField.getDocument(); document.setDocumentFilter(new DocumentFilter() { @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text; if (string.length() <= 4) { super.replace(fb, offset, length, text, attrs); } } }); panel.add(passwordField); add(panel); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JPasswordFieldDigitLimitTest(); } }
输出
广告