Java Reference
In-Depth Information
FIGURE 12.2
The Calculator
application.
The focusGained() method is called whenever either of these fields gains the input
focus (lines 32-42). In this method, the sum is calculated by adding the values in the
other two fields. If either field contains an invalid value—such as a string—a
NumberFormatException is thrown, and all three fields are reset to “0”.
The focusLost() method accomplishes the same behavior by calling focusGained()
with the focus event as an argument.
One thing to note about this application is that event-handling behavior is not required to
collect numeric input in a text field. This is taken care of automatically by any compo-
nent in which text input is received.
Item Events
Item events occur when an item is selected or deselected on components such as buttons,
check boxes, or radio buttons. A class must implement the ItemListener interface to
handle these events.
The itemStateChanged( ItemEvent ) method is the only method in the ItemListener
interface. It takes the following form:
void itemStateChanged(ItemEvent event) {
// ...
}
To determine in which item the event occurred, the getItem() method can be called on
the ItemEvent object.
You also can determine whether the item was selected or deselected by using the
getStateChange() method. This method returns an integer that equals either the class
variable ItemEvent.DESELECTED or ItemEvent.SELECTED .
Listing 12.3 illustrates the use of item events. The FormatChooser application displays
information about a selected combo box item in a label.
Search WWH ::




Custom Search