Java Reference
In-Depth Information
36
37
// construct password field with default text
38
passwordField =
new
JPasswordField(
"Hidden text"
);
39
add(passwordField);
// add passwordField to JFrame
40
41
// register event handlers
42
TextFieldHandler handler =
new
TextFieldHandler();
textField1.addActionListener(handler);
textField2.addActionListener(handler);
textField3.addActionListener(handler);
passwordField.addActionListener(handler);
43
44
45
46
47
}
48
49
// private inner class for event handling
50
private
class
TextFieldHandler
implements
ActionListener
51
{
52
// process text field events
53
@Override
54
public
void
actionPerformed(ActionEvent event)
55
{
56
String string =
""
;
57
58
// user pressed Enter in JTextField textField1
59
if
(
event.getSource() == textField1
)
60
string = String.format(
"textField1: %s"
,
61
event.getActionCommand()
);
62
63
// user pressed Enter in JTextField textField2
64
else
if
(
event.getSource() == textField2
)
65
string = String.format(
"textField2: %s"
,
66
event.getActionCommand()
);
67
68
// user pressed Enter in JTextField textField3
69
else
if
(
event.getSource() == textField3
)
70
string = String.format(
"textField3: %s"
,
71
event.getActionCommand()
);
72
73
// user pressed Enter in JTextField passwordField
74
else
if
(
event.getSource() == passwordField
)
75
string = String.format(
"passwordField: %s"
,
76
event.getActionCommand()
);
77
78
// display JTextField content
79
JOptionPane.showMessageDialog(
null
, string);
80
}
81
}
// end private inner class TextFieldHandler
82
}
// end class TextFieldFrame
Fig. 12.9
|
JTextFields
and
JPasswordFields
. (Part 2 of 2.)
Class
TextFieldFrame
extends
JFrame
and declares three
JTextField
variables and a
JPasswordField
variable (lines 13-16). Each of the corresponding text fields is instanti-
ated and attached to the
TextFieldFrame
in the constructor (lines 19-47).