Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

204 HOUR 15:Responding to User Input


Check Box and Combo Box Events
Comboboxes andcheck boxes require the ItemListenerinterface. Call the
component’s addItemListener()method to make it generate these events.
The following statements create acheck box called superSizethat sends
out user events when selected or deselected:
JCheckBox superSize = new JCheckBox(“Super Size”, true);
superSize.addItemListener(this);

These events are received by the itemStateChanged()method, which
takes an ItemEventobject as an argument. To see which object caused the
event, you can call the event object’s getItem()method.
To determine whether a check box is selected or deselected, compare the
value returned by the getStateChange()methodto the constants
ItemEvent.SELECTEDand ItemEvent.DESELECTED. The following code is an
example for an ItemEventobject called item:
int status = item.getStateChange();
if (status == ItemEvent.SELECTED) {
// item was selected
}

To determine the value selected in a JComboBoxobject, use getItem()and
convert that value to a string, as in the following:
Object which = item.getItem();
String answer = which.toString();

Keyboard Events
When a program must reactimmediately once a key is pressed, it uses key-
board events and the KeyListenerinterface.
The first step is to register the component that receives key presses by call-
ing its addKeyListener()method. The argument of the method should be
the object that implements the KeyListenerinterface. If it is the current
class, use thisas the argument.
An object that handles keyboard events must implement three methods:

. void keyPressed(KeyEvent)—A method called the moment a key is
pressed
. void keyReleased(KeyEvent)—A method called the moment a key
is released

Free download pdf