如何在JPasswordField中键入时查看密码

时间:2016-01-15 15:48:47

标签: java swing jpasswordfield

我想创建一个JPasswordField,我可以在打字时看到这些字符, 我尝试了passtxt.setEchoChar((char) 0);,但它完全将'*'更改为文字 我不想要这个, 我希望在按字符输入时查看文本 (正如我们在移动浏览器中看到的) 感谢

import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("JPasswordField  ");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p=new JPanel();
    p.add(new JLabel("Username"));
    p.add(new JTextField(20));
     p.add(new JLabel("Password"));
    JPasswordField jpassword = new JPasswordField(20);

    p.add(jpassword);

    Checkbox c=new Checkbox("type password and click");
    c.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                jpassword.setEchoChar('*');
            } else {
                jpassword.setEchoChar((char) 0);
            }
        }
    });
    jpassword.setEchoChar((char)0); 
    p.add(c);
    f.add(p);
    f.setSize(300, 200);
    f.setVisible(true);


  }
}

1 个答案:

答案 0 :(得分:-1)

这是一个简单的解决方案。使用JTextField代替JPasswordField和String成员分别存储真实密码:

private JTextField textField = new JTextField();
private String password = "";

实施java.awt.event.KeyListener,并覆盖keyReleased,如下所示:

public void keyReleased(KeyEvent e) {
    if (Character.isLetter(e.getKeyChar()) || 
        Character.isDigit(e.getKeyChar())) { //Add other valid characters as needed

        //Get text and last typed character
        String text = textField.getText();
        char typed = text.charAt(text.length()-1);
        //store typed letter separately for later use
        password += (text.length() > 0) ? typed : "";

        StringBuilder sb = new StringBuilder();
        for (int c=0; c<text.length()-1; c++) {
            sb.append("*");
        }
        sb.append(typed);

        //set password with asterisks, for authentication use member: password
        textField.setText(sb.toString());
}

将监听器添加到文本字段中,您已完成。

除非输入新的字母或数字,否则会覆盖除了输入*的最后一个字符以外的所有字符。