0

I have a JPasswordField in my java code, I want that the JPasswordField should only get 7 characters as input from user not greater than 7 characters. Please tell how to do this.

user3808922
  • 61
  • 1
  • 1
  • 3

1 Answers1

0

Add ActionListener to the JPasswordField to do this:

 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!");
        }
    }
});

Or use the 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!");
        }
    }
});
SparkOn
  • 8,806
  • 4
  • 29
  • 34
  • This does not prevent the user from entering more than 7 characters like user3808922 asked for. He should use a KeyListener and listen to the keyTyped event. This way he can react on every character entered in the password field. – Tom Jul 12 '14 at 17:19