JTextField Class

Package: javax.swing

Using JTextField creates a text field, which is a box in which the user can type text. Figure 5-13 shows an example of a typical text field.

9781118239742-fg0513.tif

Figure 5-13

Constructors

Constructor

Description

JTextField()

Creates a new text field

JTextField(int cols)

Creates a new text field with the specified width

JTextField(String text, int cols)

Creates a new text field with the specified width and initial text value

Methods

Method

Description

String getText()

Gets the text value entered in the field.

void requestFocus()

Asks for the focus to be moved to this text field.

void setColumns(int cols)

Sets the size of the text field. (It’s better to do this in the constructor.)

void setEditable(boolean value)

If false, makes the field read-only.

void setText(String text)

Sets the field’s text value.

void setToolTipText(String text)

Sets the tooltip text that’s displayed if the user rests the mouse over the text field for a few moments.

When you create a text field by calling a constructor of the JTextField class, you can specify the width of the text field and an initial text value, as in these examples:

JTextField text1 = new JTextField(15);

JTextField text2 = new JTextField(“Initial Value”, 20);

The width is specified in columns, which is a vague and imprecise measurement that’s ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.