/* * File: TextFieldTest.java * * Create an editable text field (i.e., a one-line text area) * * Copyright: Northeast Parallel Architectures Center * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; public class TextFieldTest extends JApplet { // label1 and label2 are labels for the two textfields username and password // when "enter" is pressed in either textfield, display the text in label3 JLabel label1, label2, label3; JTextField username; JPasswordField password; ImageIcon icon1, icon2; private Font f = new Font ("Dialog", Font.BOLD, 24); public void init() { try { icon1=new ImageIcon(new URL("http://www.npac.syr.edu/projects/webtech/java/examples1.2/textfieldtest/secure.gif")); icon2=new ImageIcon(new URL("http://www.npac.syr.edu/projects/webtech/java/examples1.2/textfieldtest/stranger.gif")); } catch (Exception e){} // this example shows how to use a separate class as the event listener TextFieldHandler handler = new TextFieldHandler( this ); getContentPane().setLayout(new FlowLayout()); getContentPane().setBackground( Color.white ); setFont (f); label1 = new JLabel( "Username:", icon2, JLabel.LEFT ); label1.setFont(f); username = new JTextField( 20 ); username.setFont(f); username.addActionListener( handler ); label2 = new JLabel( "Password:", icon1, JLabel.LEFT ); label2.setFont(f); password = new JPasswordField( 20 ); password.setFont(f); password.setEchoChar( '*' ); password.addActionListener( handler ); // this layout manager uses intial text to size the label label3 = new JLabel (" "); label3.setFont(f); getContentPane().add( label1 ); getContentPane().add( username ); getContentPane().add( label2 ); getContentPane().add( password ); getContentPane().add( label3 ); } } class TextFieldHandler implements ActionListener { private TextFieldTest applet; public TextFieldHandler( TextFieldTest a ) { applet = a; } public void actionPerformed( ActionEvent event ) { String text; // respond to text enter for the two textfields by showing in label3 if ( applet.username == event.getSource() ) { text = applet.username.getText(); applet.label3.setText("Your username: " + text); } if ( applet.password == event.getSource() ) { text = applet.password.getText(); applet.label3.setText("Your password: " + text); // you can also display text in the browser status bar applet.showStatus( "Text: " + text ); } } }