Java Documentation

JTextField: Single-line Text Input

JTextField is used to accept a single line of text input from the user, such as a name or a short value. It is usually paired with a label.

Example: JLabel with a JTextField

This example creates a label and a single-line text field. The label tells the user what to type, and the text field is where they enter the text.

JTextFieldDemo.java
import javax.swing.*;
import java.awt.*;

class MyFrame extends JFrame {
    MyFrame() {
        setTitle("Componets - JTextField");

        JTextField tf1 = new JTextField(10);
        // Here in the TextField 10 defines approx 10 character/columns can display
        JLabel l1 = new JLabel("Enter Text:");

        add(l1); // Label first
        add(tf1);

        setLayout(new FlowLayout());
        setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class JTextFieldDemo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
Reference & full codeView on GitHub

What is JTextField?

A JTextField is a component for single-line text input. It is typically used for short values like names, IDs, or numbers. The user can type and edit text inside it.

  • Displays one line of editable text.
  • Often placed next to a descriptive label.
  • Text can be read in code using methods like getText().

Line-by-line: Understanding the JTextField example

We again use the same JFrame pattern. Here we focus on the text field creation and its relationship with the label.

JTextField tf1 = new JTextField(10);

Creates a text field that can display roughly 10 characters at a time. The number is the column count, not a strict character limit.

JLabel l1 = new JLabel("Enter Text:");

Creates a label that tells the user what to type into the corresponding text field.

add(l1);
add(tf1);

Adds the label first and then the text field to the frame. WithFlowLayout, they appear next to each other in a row.

setLayout(new FlowLayout());

Uses FlowLayout so components are arranged from left to right like words in a sentence.

Where JTextField is used

Single-line text fields are used everywhere: login forms, search boxes, and small input dialogs. In later sections we will read values fromJTextField and validate user input.