/** A GUI program that demonstrates JTextField and
  JPasswordField, and the associated event processing
  (taken from Deitel & Deitel, Java: How to program", 
  3rd ed.. Prentice-Hall, 2002)
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldTest extends JFrame {
  private JTextField textField1, textField2, textField3;
  private JPasswordField passwordField;

  /** a constructor that sets up the GUI window */
  public TextFieldTest() {
    // provide title for the JFrame
    super("Testing JTextField and JPasswordField"); 

    Container container = getContentPane();
    container.setLayout(new FlowLayout());

    // construct textfield with default sizing
    textField1 = new JTextField(10);
    container.add(textField1);

    // construct textfield with default text
    textField2 = new JTextField("Enter text here");
    container.add(textField2);

    // construct textfield with default text and
    // 20 visible elements and no event handler
    textField3 = new JTextField("Uneditable text field", 20);
    textField3.setEditable(false);
    container.add(textField3);

    // construct passwordfield with dault text
    passwordField = new JPasswordField("Hidden text");
    container.add(passwordField);

    // register event handler
    TextFieldHandler handler = new TextFieldHandler();
    textField1.addActionListener(handler);
    textField2.addActionListener(handler);
    textField3.addActionListener(handler);
    passwordField.addActionListener(handler);

    setSize(325, 100);
    setVisible(true);
  }

  /** start the Java application */
  public static void main(String[] args) {
    TextFieldTest application = new TextFieldTest();

    application.setDefaultCloseOperation(
      JFrame.EXIT_ON_CLOSE);
  }

  /** a private inner class for event handling */
  private class TextFieldHandler implements ActionListener {

    /* must implement the method actionPerformed() to handle 
       events of user pressing the Enter key inside text field */
    public void actionPerformed(ActionEvent event) {
      String str = "";

      // if Enter is pressed inside textField1
      if (event.getSource() == textField1) 
        str = "textField1: " + event.getActionCommand();

      // if Enter is pressed inside textField2
      else if (event.getSource() == textField2) 
        str = "textField2: " + event.getActionCommand();

      // if Enter is pressed inside textField3
      else if (event.getSource() == textField3) 
        str = "textField3: " + event.getActionCommand();

      else if (event.getSource() == passwordField) {
        JPasswordField pwd =
          (JPasswordField)event.getSource();
        str = "passwordField: " + 
              new String(pwd.getPassword());
      }

      JOptionPane.showMessageDialog(null, str);
    }
  } // end of inner class TextFieldHandler
}
   

