Creating Text Fields by Using JTextField Class

In this tutorial, you will learn how to use JTextField class to create text filed widgets.

The text field is one of the most important widgets that allows the user to input text value in a single line format. To create a text field widget in Java Swing, you use JTextField class.

Here are the constructors of the JTextField class:

JTextField ConstructorsMeaning
public JTextField()Creates a new text field.
public  JTextField(Document doc, String text, int columns)Creates a new text field with given document and number of columns.
public  JTextField(String text)Creates a new text field with a given text.
public  JTextField(int columns)Creates a new text field with a given columns.
public  JTextField(String text, int columns)Creates a new text field with given text and number of columns.

Example of creating text fields

In this example, we will create two simple text fields: first name and last name as the picture below:

JTextField Demo
package jtextfielddemo; import javax.swing.*; public class Main { public static void main(String[] args) { final JFrame frame = new JFrame("JTextField Demo"); JLabel lblFName = new JLabel("First Name:"); JTextField tfFName = new JTextField(20); lblFName.setLabelFor(tfFName); JLabel lblLName = new JLabel("Last Name:"); JTextField tfLName = new JTextField(20); lblLName.setLabelFor(tfLName); JPanel panel = new JPanel(); panel.setLayout(new SpringLayout()); panel.add(lblFName); panel.add(tfFName); panel.add(lblLName); panel.add(tfLName); SpringUtilities.makeCompactGrid(panel, 2, 2, //rows, cols 6, 6, //initX, initY 6, 6); //xPad, yPad frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); frame.getContentPane().add(panel); frame.setVisible(true); } }
Code language: JavaScript (javascript)

In order to run the demo application, you’ll need SpringUtilities class. Click the following link to download file.

Java Swing Spring Utilities (4962 downloads)