# Java: JTextField

## Description

`javax.swing.JTextField` has two uses.

- Input. The user can enter one line of text (a String)
- Output. To display one line of text.

If you need a component that displays or allows entry of more than one line, use a `JTextArea`.

## To use a JTextField for Input

1. Declare a JTextField as an instance variable. Reason: If it's an instance variable, it can be seen in all methods in the class.
2. Assign an initial value to this variable by calling the JTextField constructor. Specify the approximate field width in the constructor. Example:

       JTextField yourInpuFieldt = new JTextField(16);

3. Add the text field to a container.

       content.add(yourInputField);

   or to add it to a `JPanel p`

       p.add(yourInputField);

4. Input is done by calling the `getText()`.
   1. Get the string in the text field by calling `yourTextField.getText()` method whenever you need it. This is probably the most common way.

          String x = yourInputField.getText();

   2. Attach an action listener to the text field. It is called whenever the user types Enter in that field. The listener can then get the text and process it.

## To use a JTextField for Output

Using a JTextField for output is almost the same as for input, but . . .

1. Set the text field with `yourTextField.setText(someString)`
2. If it's only for output, call `.setEditable(false)` so the user can't change the field.

Here is the sequence.

1. Declare and initialize a JTextField as a field variable (instance variable). Example:

       JTextField myOutput = new JTextField(16);

   You can also set the initial value in the field

       JTextField myOutput = new JTextField("someInitialValue", 20);

2. Add the text field to a container. For example, to add it to JPanel p.

       p.add(myOutput);

3. Setting the value of the text field. Whenever you want put a string value in the text field, call `myOutput.setText("Some text")`.

       myOutput.setText("some text");

## Constructors

`JTextField tf = new JTextField(int columns);`
  The number of columns is approximate because the width of text depends on the font and width of individual characters.
`JTextField tf = new JTextField(String initial);`
  This puts the initial String in the JTextField. The size of the JTextField is set from this String.
`JTextField tf = new JTextField(String initial, int columns);`
  This creates a JTextField columns wide with value initial.

## Common methods

Here are some of the most common methods use with text fields: Assume these declarations

        JTextField tf;
        ActionListener listener;
        String s, text;
        Font f;

        //--- When used for input.
        s = tf.getText(); // gets the text from the JTextField
        tf.addActionListener(listener); // Optional listener intialization.

        //--- When used for output.
        tf.setText(text); // Sets text in the JTextField.
        tf.setEditable(false);   // Initialization to disallow user changes.

        //--- To change the appearance.
        tf.setHorizontalAlignment(align); // See below for possible values.
        tf.setFont(f);      // sets the font for the text

## Appearance of a JTextField - font, alignment

- `yourField.setFont(Font f);` sets the font for the text. Often numbers are aligned to the right (eg, in the display of a calculator), and text is aligned to the left.
- `yourField.setHorizontalAlignment(align);` sets the alignment of the text in the field, where align is one of these values: `JTextField.LEFT` (the default), `JTextField.CENTER`, or `JTextField.RIGHT`.

## Example

    JTextField userID;   // declare a field
    . . .
    userID = new JTextField(8); // create field approx 8 columns wide.
    p.add(userID);              // add it to a JPanel

    userID.addActionListener(
        new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ... // THIS CODE IS EXECUTED WHEN RETURN IS TYPED
            }
        }
    );

## Interface Guideline

In addition to getting the ActionEvent when the user types an Enter in the JTextField, you should also have a button which the user can use to cause the same action because many users will not know that Enter in a JTextField will cause an event.

## Use JPasswordField for passwords

Use a `JPasswordField` component for a field where the characters the person enters are replaced by some other character. JPasswordField is a subclass of JTextField.

## Use JFormattedTextField to restrict input format

The `JPasswordField` subclass of `JTextField` can be used to restrict the input to particular values. See How to Use Formatted Text Fields.

## Additional methods

Because JTextField is a child class of JTextComponent, you can use the methods in the TextComponent class, for example, to find and set the caret position or selected text.

## Additional events

Normally you would use an `ActionListener` to be notified when the user types the Enter key. If you need to, you can use a listener for the Document that is being displayed. These listeners can notify you about each character, selection, cursor movement, or change.

## Focus

To select a JTextField so that user typing occurs in that field, you must give the JTextField focus. For example, the `nameField` JTextField can be given focus with:

    nameField.requestFocus();