Java Reference
In-Depth Information
Much of the program will be familiar, but a few parts warrant special attention. First,
notice that the action command associated with the text field is set to "myTF" by the fol-
lowing line:
After this line executes, the action command string will always be "myTF" no matter what
text is currently held in the text field. Therefore, the action command generated by jtf will
not accidentally conflict with the action command associated with the Reverse push but-
ton. The actionPerformed( ) method makes use of this fact to determine what event has
occurred. If the action command string is "Reverse", it can mean only one thing: that the
Reverse push button has been pressed. Otherwise, the action command was generated by
the user pressing ENTER while the text field had input focus.
Finally, notice this line from within the actionPerformed( ) method:
As explained, when the user presses ENTER while focus is inside the text field, an Ac-
tionEvent is generated and sent to all registered action listeners, through the actionPer-
formed( ) method. For TFDemo , this method simply obtains the text currently held in the
text field by calling getText( ) on jtf . It then displays the text through the label referred to
by jlabContents .
Create a JCheckBox
After the push button, perhaps the next most widely used control is the check box. In
Swing, a check box is an object of type JCheckBox . JCheckBox inherits AbstractButton
and JToggleButton . Thus, a check box is, essentially, a special type of button.
JCheckBox defines several constructors. The one used here is
JCheckBox(String str )
It creates a check box that has the text specified by str as a label.
When a check box is selected or deselected (that is, checked or unchecked), an item
event is generated. Item events are represented by the ItemEvent class. Item events are
handled by classes that implement the ItemListener interface. This interface specifies only
one method: itemStateChanged( ) , which is shown here:
void itemStateChanged(ItemEvent ie )
Search WWH ::




Custom Search