Swing has two classes for getting text input from a user. They both
extend the abstract class JTextComponent.
As you might expect with an abstract class, you'll find the common methods
here, such as setText(String s), getText(), and setEditable(Boolean
b).
JTextField
is designed for one line of text. Use this in an input form, to get
a phone number, for example.
JTextArea
is designed for multiple lines of text. Use this in a form to get
a longer description, a text message, etc.
JTextField
Take a look at the constructors for JTextField on the Javadoc (linked above).
The most simple instantiation is: JTextField myText = new JTextField();
Yep, it is the same thing we do for all other objects, we simply call a
constructor.
Then, to add txtAddress to a JPanel, we simply use the add() method of
the panel. Say we have a previosly declared and instantiated JPanel
named pnlFormPanel. We can add txtAddress like so:
pnlFormPanel.add(txtAddress):
Or, we can use the visual editor in Forte' to do the same thing.
JTextAreas are nearly identical. One exception - take a look at the
constructor. We can specify a number of rows as well as columns,
since JTextAreas are designed to accept multiple lines of text.
Commonly used methods
To set the text that displays in one of these components, we use the setText(String
s) method. For example:
txtAddress.setText("L209 Sander Hall");
Now the text field will display L209 Sander Hall.
To get the text and assign it to a variable or pass it to another method,
we use the getText() method. For example:
String strAddress = txtAddress.getText();
Now the String variable strAddress will contain whatever text
is in the txtAddress object.