Java Reference
In-Depth Information
securely ask the user for a password. One useful tool for this process is the JPassword
Field component from Swing. Example 4-1 demonstrates a Swing-based Authentica
tor subclass that brings up a dialog to ask the user for their username and password.
Example 4-1. A GUI authenticator
import javax.mail.* ;
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
public class MailAuthenticator extends Authenticator {
private JDialog passwordDialog = new JDialog ( new JFrame (), true );
private JTextField usernameField = new JTextField ( 20 );
private JPasswordField passwordField = new JPasswordField ( 20 );
private JButton okButton = new JButton ( "OK" );
public MailAuthenticator () {
this ( "" );
}
public MailAuthenticator ( String username ) {
JLabel mainLabel = new JLabel (
"Please enter your username and password: " );
JLabel userLabel = new JLabel ( "Username: " );
JLabel passwordLabel = new JLabel ( "Password: " );
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 );
pane . add ( p4 );
passwordDialog . pack ();
ActionListener listener = new HideDialog ();
okButton . addActionListener ( listener );
usernameField . addActionListener ( listener );
passwordField . addActionListener ( listener );
}
class HideDialog implements ActionListener {
Search WWH ::




Custom Search