如何防止 JTextField 计算退格键

how to prevent the JTextField from counting the backspace

我试图确保用户在 JTextField 中输入了强密码。然而,它运行良好,但在单击时计算退格键、shift 键和 ctrl

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

-例如,如果用户键入 12345678,“密码正确”将出现在标签中,但如果他单击退格键并删除 8,“密码正确”仍将出现在标签中,因为它删除了8 但添加了退格键所以长度仍然是 8

-当用户键入 1234567 然后单击 ctrl 时,会出现“密码正确”,因为它计算了 ctrl 的单击

but it counts the arrows and the backspace when clicked

您的逻辑应基于文本字段中的文本。

不要使用 KeyListener。

您可以使用 DocumentListener。每次在文本字段中添加或删除文本时都会生成一个事件。

阅读有关 How to Write a DocumentListener 的 Swing 教程部分,了解更多信息和工作示例。

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

如果您想在输入文本时对其进行编辑,那么您应该:

  1. 使用JFormattedTextField,或
  2. 使用 DocumentFilter.