JTextField in Java Swing

JTextField is a component in the Java Swing library that allows users to enter and edit text. It is a simple text input field that can be added to a user interface to allow users to enter text data.

To create a JTextField in Java Swing, we can use the following code:

JTextField textField = new JTextField();

This will create a new JTextField object with default values. We can customize the appearance and behavior of the text field by setting various properties, such as the size, font, text color, background color, and border. For example, to set the size of the text field, we can use:

textField.setPreferredSize(new Dimension(200, 30));

This will set the preferred size of the text field to 200 pixels wide and 30 pixels high. We can add the text field to a container, such as a JPanel or JFrame, using the add() method:

JPanel panel = new JPanel();
panel.add(textField);

This will add the text field to the panel. Users can now enter and edit the text in the field by clicking on it and typing. We can retrieve the text entered by the user using the getText() method:

String text = textField.getText();

This will return a String object containing the text entered by the user.

The complete example code is given below:

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

public class JTextFieldDemo {
    public static void main(String[] args) {
        // Create a new JFrame
        JFrame frame = new JFrame("JTextField Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Create a new JPanel
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        
        // Create a new JTextField
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(200, 30));
        
        // Add the JTextField to the JPanel
        panel.add(textField);
        
        // Add the JPanel to the JFrame
        frame.getContentPane().add(panel);
        
        // Set the size of the JFrame and make it visible
        frame.setSize(300, 100);
        frame.setVisible(true);
    }
}

Output:

JTextField in Java Swing