JTextField Class

A text field is used to allow a user to enter data using a graphical user interface.


The JTextField class is imported by the statement:

import javax.swing.*;


JTextField(int columns)
JTextField(String text, int columns)

The columns parameter specifies the width of the field. The width of the text field (in columns) is an inexact measure and does not necessarily indicate the number of characters that can be displayed within the text field. If the text is too long to fit within the text field, the user can scroll left or right to view the hidden portions.

The text parameter is a string variable or a literal string (enclosed by quotation marks) and specifies the text that is to appear in the text field. To create a blank text field either use the first constructor or use the second constructor with a text parameter of "" (an empty string).

Note: There is a default constructor, JTextField(), that will create a blank text field with zero columns. If you use the default constructor then you should use the setColumns( ) method to specify the number of columns in the text field. You should always specify the number of columns you want in a text field.

Selected Methods

String getText()

Return the text currently being displayed in the text field.

setText(String text)

Specify the text to be displayed.

setFont(Font f)

Specify the font to use.


Request that the text field be made the active component.


Notify this application when the user presses the Return key in the text field.

Example 1

The Java code below creates a text field that is 20 columns wide, containing the text "Wilmore" displayed using a plain, mono-spaced 12-point font:

private JTextField txtCity;
txtCity = new JTextField(20);
txtCity.setFont(new Font("Monospaced", Font.PLAIN, 12));

See also: Font