java - 有 JPasswordField 的替代方案吗?

标签 java swing passwords

当输入类似密码时

yeast bulk seize is shows pain

每个人都可以听到敲击空格键的声音,因此在密码字段中显示空格似乎也是合乎逻辑的。所以我想要一些能够展示的东西

***** **** ***** ** ***** ****

而不是

******************************

这将使输入更容易,同时几乎不会降低安全性。

<小时/>

更新

更新 Riduidel 的评论之前请三思。当Bruce Schneier writes “是时候以明文形式显示大多数密码了”,那么显示一小部分密码也必须是正确的。特别是展示了只需聆听即可捕捉到的部分。

最佳答案

这是使用 setEchoChar() 的变体使密码在预定义的时间内可见:例如三秒。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/** @see http://stackoverflow.com/questions/5339702 */
public class PasswordTest {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }

    private static void createAndShowGui() {
        JFrame jf = new JFrame("Test Password");
        JPasswordField jpwd = new JPasswordField();
        TimedPasswordListener tpl = new TimedPasswordListener(jpwd);
        jpwd.getDocument().addDocumentListener(tpl);
        jf.add(jpwd);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);
        jf.pack();
        jf.setVisible(true);
    }
}

class TimedPasswordListener implements DocumentListener, ActionListener {

    private Timer timer = new Timer(3000, this);
    private char echoChar;
    private JPasswordField pwf;

    public TimedPasswordListener(JPasswordField jp) {
        pwf = jp;
        timer.setRepeats(false);
    }

    public void insertUpdate(DocumentEvent e) {
        showText(e);
    }

    public void removeUpdate(DocumentEvent e) {
        showText(e);
    }

    public void changedUpdate(DocumentEvent e) {}

    public void showText(DocumentEvent e) {
        if (0 != pwf.getEchoChar()) {
            echoChar = pwf.getEchoChar();
        }
        pwf.setEchoChar((char) 0);
        timer.restart();
    }

    public void actionPerformed(ActionEvent e) {
        pwf.setEchoChar(echoChar);
    }
}

关于java - 有 JPasswordField 的替代方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5339702/

相关文章:

php - 关于login.php中的while循环

java - 匹配两个 EditText 条目不适用于星号 (fieldOne.matches(fieldTwo))

java - Apache Camel : Notification on CamelContext stop

java - Android Firebase 存储 : How to get file size from firebase storage file url before downloading it?

java - 为什么我必须为二叉树的递归插入显式设置左/右子节点?

java - JComponent 不可见

java - 如何检查 JTable JAVA 中是否存在行?

java - 需要更改具有不同形状的 JButton 的颜色

java - 使用安全随机生成随 secret 码

java - "Reverse Order"中二叉树逐行层序遍历,时间复杂度O(n)