public PasswordAuthentication(String userName, char[] password)
每个都是通过getter 方法被访问的:
public String getUserName( )
public char[] getPassword( )
JPasswordField 类
Swing中JPasswordField 组件有个用来向用户获取密码的有用工具:
public class JPasswordField extends JTextField
这个轻量级组件和文本框的行为几乎是一样的。但是用户输入的会以“*”形式显示出来。这样的话,就可以防止其他人在后面看见用户输入的密码了。
JPasswordField 也用char 数组来存放密码,这样当你不再需要是,你就可以清空它了。方法getPassword( ) 用来返回密码:
public char[] getPassword( )
不然的话,大多数时候你得使用继承超类JTextField 后得到的方法。例子7-13展示了一个来自Swing的Authenticator 的子类,它生成一个对话框向用户获取他的用户名和密码。下面的大多数代码都是用来生成GUI。JPasswordField 提取密码,JTextField 提取用户名。图7-4就是下面代码所生成的一个简单的对话框。
Example 7-13. A GUI authenticator
package com.macfaq.net;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogAuthenticator extends Authenticator {
private JDialog passwordDialog;
private JLabel mainLabel
= new JLabel("Please enter username and password: ");
private JLabel userLabel = new JLabel("Username: ");
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField usernameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public DialogAuthenticator( ) {
this("", new JFrame( ));
}
public DialogAuthenticator(String username) {
this(username, new JFrame( ));
}
public DialogAuthenticator(JFrame parent) {
this("", parent);
}
public DialogAuthenticator(String username, JFrame parent) {
this.passwordDialog = new JDialog(parent, true);
Container pane = passwordDialog.getContentPane( );
pane.setLayout(new GridLayout(4, 1));
pane.add(mainLabel);
JPanel p2 = new JPanel( );
p2.add(userLabel);
p2.add(usernameField);
usernameField.setText(username);
pane.add(p2);
JPanel p3 = new JPanel( );
p3.add(passwordLabel);
p3.add(passwordField);
pane.add(p3);
JPanel p4 = new JPanel( );
p4.add(okButton);
p4.add(cancelButton);
pane.add(p4);
passwordDialog.pack( );
ActionListener al = new OKResponse( );
okButton.addActionListener(al);
usernameField.addActionListener(al);
passwordField.addActionListener(al);
cancelButton.addActionListener(new CancelResponse( ));
}
private void show( ) {
String prompt = this.getRequestingPrompt( );
if (prompt == null) {
String site = this.getRequestingSite( ).getHostName( );
String protocol = this.getRequestingProtocol( );
int port = this.getRequestingPort( );
if (site != null & protocol != null) {
prompt = protocol + "://" + site;