Page 687 - Introduction to Programming with Java: A Problem Solving Approach
P. 687
16.7 JTextField Component User Interface
The JTextField component displays a rectangle and allows the user to enter text into the rectangle. Here’s an example:
Implementation
To create a JTextField object, call the JTextField constructor like this:
JTextField <JTextField-reference> = new JTextField(<default-text>, <width>);
The default-text is the text that appears in the text box by default. The width is the number of characters that can display in the text box at one time. If the user enters more characters than can display at one time, then the leftmost characters scroll off the display. If the default-text argument is omitted, then the empty string is used as the default. If theAwidptharguomentPisDomFitted,Ethnenhthae bnoxc’s weidrth is slightly greater than the width of the default text.
To add a JTextField object to your JFrame window, use this syntax:
add(<JTextField-reference>);
The JTextField class needs the javax.swing package, but that should be available already, since it’s needed for the JFrame class.
Methods
The JTextField class has quite a few methods. Here are API headings and descriptions for some of the more useful ones:
public String getText()
Returns the text box’s contents.
public void setText(String text)
Assigns the text box’s contents.
public void setEditable(boolean flag)
Makes the text box editable or non-editable.
public void setVisible(boolean flag)
16.7 JTextField Component 653
t
t
e
Makes the text box visible or invisible.
e
x
x
t
t
b
b
o
o
x
x
o
o
p
p
t
t
i
i
o
o
n
na
al
l