JPasswordField中指定的字符数

时间:2014-07-12 16:46:51

标签: java

我的java代码中有一个JPasswordField,我希望JPasswordField只能从用户输入不超过7个字符的7个字符作为输入。请告诉我们如何做到这一点。

1 个答案:

答案 0 :(得分:0)

将ActionListener添加到JPasswordField以执行此操作:

 passwordField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        JPasswordField field = (JPasswordField) event.getSource();
        char[] password = field.getPassword();

        if (password.length > 7) {
            System.out.println("Password must contain 7 characters!");
        }
    }
});

或使用keyListener

passwordField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyReleased(KeyEvent event) {
        JPasswordField field = (JPasswordField) event.getSource();
        char[] password = field.getPassword();

        if (password.length > 7) {
            System.out.println("Password must contain 7 characters!");
        }
    }
});