Home ยป Working with JTextField in Java Swing

Working with JTextField in Java Swing

JTextField is a commonly used component in Java Swing for taking user input in the form of a single line of text. It is widely used in forms, login screens, and user interfaces where text input is required.

In this tutorial, we will explore the various features of JTextField, including how to create text fields, handle user input, customize their appearance, and more.

Topics Covered:

1. Creating a Basic JTextField

You can create a JTextField by using the constructor, specifying the number of columns (width) of the text field.

Example 1: Basic JTextField

import javax.swing.*;

public class JTextFieldExample1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Basic JTextField Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            // Create a JTextField with a width of 20 columns
            JTextField textField = new JTextField(20);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.setVisible(true);
        });
    }
}

Explanation:

A JTextField is created with 20 columns, which defines its width.
The JTextField is added to the JFrame and displayed.

2. Handling Input Events from JTextField

You can handle input events by adding an ActionListener to the JTextField. This allows you to capture and process the text when the user presses “Enter”.

Example 2: Handling Input from JTextField

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTextFieldExample2 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JTextField Input Event Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);
            JLabel label = new JLabel("Enter your name:");

            // Add an ActionListener to capture input when "Enter" is pressed
            textField.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String input = textField.getText();
                    label.setText("Hello, " + input + "!");
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

An ActionListener is added to the JTextField. When the user presses “Enter”, the entered text is retrieved using getText() and displayed in the label.

3. Setting Initial Text and Retrieving User Input

You can set initial text in the JTextField using setText() and retrieve the entered text using getText().

Example 3: Setting and Retrieving Text

import javax.swing.*;

public class JTextFieldExample3 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Setting and Retrieving Text Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField("Enter your name", 20);
            JButton button = new JButton("Submit");
            JLabel label = new JLabel();

            // Set an ActionListener for the button to retrieve text from the JTextField
            button.addActionListener(e -> {
                String input = textField.getText();
                label.setText("Entered: " + input);
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.add(button);
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

The initial text “Enter your name” is set in the JTextField using setText().
When the button is clicked, the input is retrieved using getText() and displayed in the label.

4. Limiting the Number of Characters

You can limit the number of characters a user can enter in a JTextField by using a DocumentFilter or by subclassing PlainDocument.

Example 4: Limiting Characters in JTextField

import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;

public class JTextFieldExample4 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Limit Characters Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);
            JLabel label = new JLabel("Max 10 characters:");

            // Limit the JTextField to 10 characters
            ((AbstractDocument) textField.getDocument()).setDocumentFilter(new DocumentFilter() {
                @Override
                public void replace(FilterBypass fb, int offset, int length, String text, javax.swing.text.AttributeSet attrs)
                        throws javax.swing.text.BadLocationException {
                    if ((fb.getDocument().getLength() + text.length() - length) <= 10) {
                        super.replace(fb, offset, length, text, attrs);
                    }
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(label);
            frame.add(textField);
            frame.setVisible(true);
        });
    }
}

Explanation:

A DocumentFilter is used to limit the number of characters a user can enter in the JTextField to 10.
The replace() method ensures that no more than 10 characters are allowed in the field.

5. Customizing the Appearance of JTextField

You can customize the appearance of a JTextField by changing its font, background color, and text color.

Example 5: Customizing JTextField Appearance

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

public class JTextFieldExample5 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom JTextField Appearance Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);

            // Customize the appearance of the JTextField
            textField.setFont(new Font("Serif", Font.BOLD, 16));
            textField.setForeground(Color.BLUE);
            textField.setBackground(Color.LIGHT_GRAY);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.setVisible(true);
        });
    }
}

Explanation:

The font, foreground (text color), and background color of the JTextField are customized using setFont(), setForeground(), and setBackground().

6. Adding Placeholders to JTextField

You can add placeholder text to a JTextField by using a FocusListener that shows placeholder text when the field is empty and removes it when the field gains focus.

Example 6: Adding Placeholder Text

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class JTextFieldExample6 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Placeholder Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);
            textField.setText("Enter your name");

            // Add a FocusListener to show and remove placeholder text
            textField.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent e) {
                    if (textField.getText().equals("Enter your name")) {
                        textField.setText("");
                        textField.setForeground(Color.BLACK);
                    }
                }

                @Override
                public void focusLost(FocusEvent e) {
                    if (textField.getText().isEmpty()) {
                        textField.setText("Enter your name");
                        textField.setForeground(Color.GRAY);
                    }
                }
            });

            textField.setForeground(Color.GRAY); // Placeholder text color

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.setVisible(true);
        });
    }
}

Explanation:

A FocusListener is added to the JTextField to display placeholder text (“Enter your name”) when the field is empty and remove it when the field gains focus.
The text color is set to gray for the placeholder text.

7. Handling Focus Events in JTextField

You can use a FocusListener to handle focus events for JTextField. This allows you to perform actions when the text field gains or loses focus.

Example 7: Handling Focus Events

import javax.swing.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class JTextFieldExample7 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Focus Events Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);
            JLabel label = new JLabel("Focus state: ");

            // Add a FocusListener to handle focus events
            textField.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent e) {
                    label.setText("Focus state: Gained");
                }

                @Override
                public void focusLost(FocusEvent e) {
                    label.setText("Focus state: Lost");
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

A FocusListener is used to detect when the JTextField gains or loses focus.
The label is updated to indicate whether the text field currently has focus.

8. Validating Input in JTextField

You can validate the input in JTextField by using an ActionListener or FocusListener to check if the input matches specific criteria, such as being numeric or within a certain range.

Example 8: Validating Input in JTextField

import javax.swing.*;

public class JTextFieldExample8 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Input Validation Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            JTextField textField = new JTextField(20);
            JButton button = new JButton("Validate");
            JLabel label = new JLabel("Enter a number:");

            // Validate input when the button is clicked
            button.addActionListener(e -> {
                try {
                    int number = Integer.parseInt(textField.getText());
                    label.setText("Valid number: " + number);
                } catch (NumberFormatException ex) {
                    label.setText("Invalid input! Please enter a number.");
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(textField);
            frame.add(button);
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

The input is validated when the button is clicked. If the input is a valid number, it is displayed; otherwise, an error message is shown.
Integer.parseInt() is used to check if the input is a valid integer.

Conclusion

JTextField is a fundamental component in Java Swing for text input. You can handle input events, validate user input, and customize its appearance. By using various listeners and event handling mechanisms, you can create dynamic and interactive user interfaces.

Summary of Key Points:

Basic JTextField: Create a text field using new JTextField(columns) for text input.
Input Handling: Use ActionListener to capture and process user input when the “Enter” key is pressed.
Setting and Retrieving Text: Use setText() to set default text and getText() to retrieve user input.
Limiting Characters: Use DocumentFilter to limit the number of characters that can be entered.
Customizing Appearance: Modify the font, text color, and background using setFont(), setForeground(), and setBackground().
Placeholders: Add placeholder text using a FocusListener to guide the user.
Input Validation: Validate user input to ensure that it meets certain criteria.

You may also like