The size of a component . A JComponent has minimum , preferred , and maximum sizes. A layout
manager tries to place a component using its preferred size, but its size will
never be less than the minimum or more than the maximum.
In most situations, you do not have to deal with the size. But when a GUI
does not look right, you may have to change the preferred size. Look at the API
specs for JComponent , or look at activity 17-2.4 on sliders.
We found two places where it was necessary to change the preferred size
of a component: (1) in using a particular slider and (2) in using a JPanel pure-
ly as a place to put graphics, without placing any components on it.
Here is an example of the creation of a text field and its placement in the
center of the content pane of JFrame jf :
JTextField field= new JTextField("a text field", 11);
The first statement stores in field an instance of JTextField . The two argu-
ments of the constructor call are the initial value of the text and the number of
columns. The number of columns is only an approximation to the number of
characters because characters have different widths. JTextField has other con-
structors; look them up in the API.
There are many methods for dealing with text fields. We discuss some of
them below. Most of these methods are called in response to the user doing
something in the GUI, like clicking a button with the mouse. You can create a
JFrame with a text field on it in DrJava's Interactions pane and then experiment
with these methods, with calls in the Interactions pane. So you do not have to
wait until we discuss handling events before seeing the methods in action.
Making the text field uneditable
A text field is editable —the user can type in it. To make is uneditable, exe-
cute the method call:
field.setEditable( false );
To make field editable again, call the same function with argument true .
Playing with the text
Retrieve the text from the field using String function getText() . You can
also retrieve just part of the text using a two-argument getText . For example,
the following statement stores in s the substring field[start.. start+len-1]
—that is, the len chars of text field field , beginning at position start :
String s= field.getText(start, len);
Change text field field to contain a string s using setText :