Java Reference
In-Depth Information
When the user types in a
JTextField
or a
JPasswordField
, then presses
Enter
, an
event
occurs. Our next example demonstrates how a program can perform a task
in response
to that event. The techniques shown here are applicable to all GUI components that gen-
erate events.
The application of Figs. 12.9-12.10 uses classes
JTextField
and
JPasswordField
to
create and manipulate four text fields. When the user types in one of the text fields, then
presses
Enter
, the application displays a message dialog box containing the text the user
typed. You can type only in the text field that's “in
focus
.” When you
click
a component,
it
receives the focus
. This is important, because the text field with the focus is the one that
generates an event when you press
Enter
. In this example, when you press
Enter
in the
JPasswordField
, the password is revealed. We begin by discussing the setup of the GUI,
then discuss the event-handling code.
1
// Fig. 12.9: TextFieldFrame.java
2
// JTextFields and JPasswordFields.
3
import
java.awt.FlowLayout;
4
import
java.awt.event.ActionListener;
5
import
java.awt.event.ActionEvent;
6
import
javax.swing.JFrame;
7
import
javax.swing.JTextField;
8
import
javax.swing.JPasswordField;
9
import
javax.swing.JOptionPane;
10
11
public
class
TextFieldFrame
extends
JFrame
12
{
13
private final
JTextField textField1;
// text field with set size
14
private final
JTextField textField2;
// text field with text
15
private final
JTextField textField3;
// text field with text and size
16
private final
JPasswordField passwordField;
// password field with text
17
18
// TextFieldFrame constructor adds JTextFields to JFrame
19
public
TextFieldFrame()
20
{
21
super
(
"Testing JTextField and JPasswordField"
);
22
setLayout(
new
FlowLayout());
23
24
// construct text field with 10 columns
textField1 =
new
JTextField(
10
);
25
26
add(textField1);
// add textField1 to JFrame
27
28
// construct text field with default text
textField2 =
new
JTextField(
"Enter text here"
);
29
30
add(textField2);
// add textField2 to JFrame
31
32
// construct text field with default text and 21 columns
textField3 =
new
JTextField(
"Uneditable text field"
,
21
);
textField3.setEditable(
false
);
// disable editing
33
34
35
add(textField3);
// add textField3 to JFrame
Fig. 12.9
|
JTextFields
and
JPasswordFields
. (Part 1 of 2.)