Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.10. Text Fields

5.10. Text Fields
Last updated: 25 January 2013.

This tutorial will show you how to use text fields in Java.

A text field is an instance of the class JTextField. It is a component that allows the user to type in a single line of text. An action event is fired when the user hits enter. The following sample shows a frame containing a text field and a label. When the user types in the text field and hits enter, the content of the text field is displayed in the label and the text field is cleared:

Text field

Here is the code:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;

public final class TextFields extends JFrame implements ActionListener {

private JTextField textField;
private JLabel label;

public TextFields() {


public void actionPerformed(ActionEvent e) {

private void addComponents() {
// Create the content pane
JPanel contentPane = new JPanel(new GridLayout(2, 1));

// Set up the text field
textField = new JTextField(200);

// Set up the label
label = new JLabel("What is the golden ratio?", SwingConstants.CENTER);

// Add the content pane to the JFrame

private void init() {
(200, 100);

public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextFields();

As you can see, I specified the number of columns in the constructor of the class JTextField (200). The specified value does not set the number of columns in the text field but rather determines the preferred width of the text field according to the font's size.

Generally, text fields are simply used to get input from the user. However, if you want to listen to text changes in a text field, you can register a document listener and implement the methods of the interface DocumentListener as shown below:

textField.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent e) {

public void insertUpdate(DocumentEvent e) {

public void changedUpdate(DocumentEvent e) {

You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.10. Text Fields
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.11. Formatted Text Fields

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7