public static void main (String args[]) { Frame f = new URLPassword(); f.setSize(300, 300); f.setVisible (true); }
class MyAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { final Dialog jd = new Dialog (URLPassword.this, "Enter password", true); jd.setLayout (new GridLayout (0, 1)); Label jl = new Label (getRequestingPrompt()); jd.add (jl); TextField username = new TextField(); username.setBackground (Color.lightGray); jd.add (username); TextField password = new TextField(); password.setEchoChar (´*´); password.setBackground (Color.lightGray); jd.add (password); Button jb = new Button ("OK"); jd.add (jb); jb.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) { jd.dispose(); } }); jd.pack(); jd.setVisible(true); return new PasswordAuthentication (username.getText(), password.getText()); } } }
后续技巧! 来自 Luis Blanco Gomez 代码的第 85 行(MyAuthenticator 类的返回参数)显示一个错误:
return new PasswordAuthentication (username.getText(), password.getText());
编译器将报错:
URLPass.java:88: Incompatible type for constrUCtor. Can´t convert java.lang.String to char[]. return new PasswordAuthentication ( username.getText(), password.getText());