Java Reference
In-Depth Information
FIGURE 12.3
The output of the
FormatChooser
application.
The application creates a combo box from an array of strings and adds an item listener to
the component (lines 22-25). Item events are received by the
itemStateChanged( ItemEvent ) method (lines 31-36), which changes the text of a label
based on the index number of the selected item. Index 1 corresponds with “Atom”, 2
with “RSS 0.92”, 3 with “RSS 1.0”, and 4 with “RSS 2.0”.
Key Events
Key events occur when a key is pressed on the keyboard. Any component can generate
these events, and a class must implement the KeyListener interface to support them.
There are three methods in the KeyListener interface. They include
keyPressed( KeyEvent ) , keyReleased( KeyEvent ) , and keyTyped( KeyEvent ) . They take
the following forms:
public void keyPressed(KeyEvent event) {
// ...
}
public void keyReleased(KeyEvent event) {
// ...
}
public void keyTyped(KeyEvent event) {
// ...
}
KeyEvent 's getKeyChar() method returns the character of the key associated with the
event. If no Unicode character can be represented by the key, getKeyChar() returns a
character value equal to the class variable KeyEvent.CHAR_UNDEFINED .
For a component to generate key events, it must be capable of receiving the input focus.
Text fields, text areas, and other components that take keyboard input support this auto-
matically. For other components such as labels and panels, the setFocusable( boolean )
method should be called with an argument of true :
Container pane = getContentPane();
pane.setFocusable(true);
Search WWH ::




Custom Search