【问题标题】:specified number of characters in JPasswordField [duplicate]JPasswordField 中指定的字符数 [重复]
【发布时间】:2014-07-12 16:46:51
【问题描述】:

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

【问题讨论】:

    标签: java


    【解决方案1】:

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

    【讨论】:

    • 这不会阻止用户输入超过 7 个字符,如 user3808922 要求的。他应该使用 KeyListener 并监听 keyTyped 事件。这样他就可以对密码字段中输入的每个字符做出反应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2011-11-19
    • 2012-04-18
    • 2016-10-21
    相关资源
    最近更新 更多