Search code examples
javaswingjtextfield

how to prevent the JTextField from counting the backspace


I am trying to make sure that the user enters a strong password in the JTextField. however, it works good but it counts the backspace, shift, and ctrl when clicked

            public void keyPressed(KeyEvent e) {
            // if else make sure that the user do not enter space
            if (Character.isWhitespace(e.getKeyChar())) {
                passwordMessage.setText("spaces are not allowed!!");
                passwordtext.setEditable(false);
            } else {
                passwordMessage.setText("");
                passwordtext.setEditable(true);
            }
            
            // if elseif else to make sure that the user enter a good length
            // passwordtext.getText().length() does not count the first entered so I -1 from the length
            if(passwordtext.getText().length() >= 14) { // if length is 15 or above
                passwordMessage.setForeground(Color.GREEN);
                passwordMessage.setText("password is Strong");              
            }
            else if(passwordtext.getText().length() >= 7) { // if length is 8 or above
                passwordMessage.setForeground(Color.ORANGE);
                passwordMessage.setText("password is Good");
            }
            else if(passwordtext.getText().length() < 7) { // if length is less than 8
                passwordMessage.setForeground(Color.RED);
                passwordMessage.setText("minimum password is 8 letters or digits!!");
            }
            else if(passwordtext.getText().length() == 0) { // setting the label text to be empty
                passwordMessage.setText("");
            }
        }

-for example, if the user typed 12345678 the "password is Good" will appear in the label but if he clicked backspace and removed the 8 the "password is Good" will still appear in the label because it removed the 8 but added the click of the backspace so the length is still 8

-same thing happened when the user type 1234567 and then click ctrl the "password is Good" will appear because it counts the click of the ctrl


Solution

  • but it counts the arrows and the backspace when clicked

    Your logic should be based on the text in the text field.

    Don't use a KeyListener.

    Instead you can use a DocumentListener. An event will be generated every time text is added or removed from the text field.

    Read the section from the Swing tutorial on How to Write a DocumentListener for more information and working examples.

    if (Character.isWhitespace(e.getKeyChar())) {
    

    If you want to do editing of the text as it is typed then you should either:

    1. Use JFormattedTextField, or
    2. Use a DocumentFilter.