这是一种变体,用于
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;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); }}


