Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Using a TextField


TheTextFieldclass implements a single-line text-entry area, usually called anedit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.TextFieldis a subclass ofTextComponent.TextField
defines the following constructors:

TextField( ) throws HeadlessException
TextField(intnumChars) throws HeadlessException
TextField(Stringstr) throws HeadlessException
TextField(Stringstr, intnumChars) throws HeadlessException

The first version creates a default text field. The second form creates a text field that is
numCharscharacters wide. The third form initializes the text field with the string contained
instr.The fourth form initializes a text field and sets its width.
TextField(and its superclassTextComponent) provides several methods that allow you
to utilize a text field. To obtain the string currently contained in the text field, callgetText( ).
To set the text, callsetText( ). These methods are as follows:

String getText( )
void setText(Stringstr)

Here,stris the new string.
The user can select a portion of the text in a text field. Also, you can select a portion of
text under program control by usingselect( ). Your program can obtain the currently selected
text by callinggetSelectedText( ). These methods are shown here:

String getSelectedText( )
void select(intstartIndex, intendIndex)

getSelectedText( )returns the selected text. Theselect( )method selects the characters
beginning atstartIndexand ending atendIndex–1.

Chapter 24: Using AWT Controls, Layout Managers, and Menus 719


FIGURE 24-6 Sample output from theSBDemoapplet
Free download pdf