Input with a TextField

Context

You're writing a program with a graphical user interface. You need to get a short piece of textual input from the user. Use a JTextField graphical user interface widget.

Example

When the user types text in the JTextField (the top box) followed by pressing the Enter key, the text is appended to the JTextArea (the bottom box). The JTextArea is set so the user may not edit it. In a Java-enabled browser the actual applet should appear on the left; an image of the applet on the right. This example is illustrated by the following applet.

Image of Applet
Applet Image
package Patterns.TextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TextFieldEx extends JFrame
{  // Instantiate a textfield for input and a textarea for output.
   private JTextField input = new JTextField(15);
   private JTextArea output = new JTextArea(5, 15);

   public TextFieldEx()
   {  // Register a listener with the textfield
      TextFieldListener tfListener = new TextFieldListener();
      input.addActionListener(tfListener);

      // Don't let the user change the output.
      output.setEditable(false);

      // Add all the widgets to the applet
      this.getContentPane().add(input);
      this.getContentPane().add(output);
      input.requestFocus();        // start with focus on this field
   }

   // The listener for the textfield.
   private class TextFieldListener implements ActionListener
   {  public void actionPerformed(ActionEvent evt)
      {  String inputString = input.getText();
         output.append(inputString + "\n");
         input.setText("");
      }
   }
}

Pattern

package <name-of-package>;
import javax.swing.JFrame;
import javax.swing.TextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class <name-of-class> extends JFrame
{  private JTextField <textfieldname> = new JTextField(<optional-size>);

   public void init()
   {  <textfieldname>.addActionListener(new <listenerclassname>());
      this.getContentPane().add(<textfieldname>);
   }
   
   private class <listenerclassname> implements ActionListener
   {  public void actionPerformed(ActionEvent evt)
      {  <code-to-execute-when-text-is-entered-in-text-field>
      }
   }
}

Notes

Related Patterns