// Figure 11.9, Deitel and Deitel, 7th edition
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField; // JTextField extends JTextComponent in javax.swing.text
import javax.swing.JPasswordField; // JPasswordField extends JTextField
import javax.swing.JOptionPane;

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

    public TextFieldFrame() { // zero-argument constructor
    super("Testing JTextField and JPasswordField");
    setLayout(new FlowLayout());
    textField1 = new JTextField(10); // sets width of textfield to 10 columns
    add(textField1);

    textField2 = new JTextField("Enter text here");
    add(textField2);

    textField3 = new JTextField("Uneditable text field",21);
    textField3.setEditable(false);
    add(textField3);

    passwordField = new JPasswordField("Hidden text");
    add(passwordField);

    TextFieldHandler handler = new TextFieldHandler();
    textField1.addActionListener(handler); // registering the event listener
    textField2.addActionListener(handler);
    textField3.addActionListener(handler);
    passwordField.addActionListener(handler);
    // the argument of addActionListener is an ActionListener object, which can be an
    // object of any class that implement ActionListener (as is the case below)
} // end constructor

 private class TextFieldHandler implements ActionListener { // nested class
 // Non-static nested classes are known as inner classes
 // actionPerformed method below is called when the user presses enter in any of the GUI fields
 // because the event handler object has been registered as the event handler for each of the
 // text fields
 	public void actionPerformed(ActionEvent event) {
		String string = "";
		if (event.getSource() == textField1)
		string = String.format("textField1: %s",event.getActionCommand());

		else if (event.getSource() == textField2)
		string = String.format("textField2: %s",event.getActionCommand());

		else if (event.getSource() == textField3)
		string = String.format("textField3: %s",event.getActionCommand());

		else if (event.getSource() == passwordField)
		string = String.format("passwordField: %s",new String(passwordField.getPassword()));
		// the getPassword method returns the password as an array of type char which is then
		// used as the argument to a String constructor to create the string of characters in the
		// array
		JOptionPane.showMessageDialog(null,string);
	} // end method actionPerformed
 } // end class TextFieldHanlder
} // end class TextFieldFrame