Java Reference
In-Depth Information
2. Instantiate an object of that class. This will be the event listener.
3. Register the event listener with the event source (e.g., a window or a panel).
Note that if a keyboard key is pressed and then released, then the keyPressed ,
keyReleased ,and keyTyped methods of the event listener will be called in that order.
Here is an example of creating a key listener object.
1 class MyKeyListener implements KeyListener {
public void keyPressed (KeyEvent e )
char c = e . getKeyChar () ;
if (charList . contains(c))
charList . remove((Character) c) ;
System . out . p r i n t l n ( c ha r L i s t ) ;
public void keyReleased (KeyEvent e )
public void keyTyped(KeyEvent e )
11 }
12 ...
13 MyKeyListener keyListener = new MyKeyListener () ;
Note that all three methods take as input an event. When the event occurs, the corre-
sponding method is called and the event is passed as a parameter. For key events, the event
class is KeyEvent .The getKeyChar method for the event object returns the key on which
the event occurred. Note that the cast at Line 5 of the code is required. If it is not present,
Java will take the ASCII code of the character and remove from the ArrayList the element
with that index. The keyPressed method finds the key that is pressed and removes it from
the ArrayList if present. At the end, the ArrayList is redisplayed. Note that the contains
method of the ArrayList class checks to see if the element belongs to the ArrayList .
Often, when writing event listeners, one does not want to override all the methods
of the interface that we are inheriting. For example, the interface for a mouse listener
has five methods and one rarely needs to override all of them. To help the programmer,
abstract classes were added to the Java library that contain empty implementation of the
methods for most interfaces. For example, there is a KeyAdapter class that contains empty
implementation of the three methods of the KeyListener interface. Here is an example of
how the class can be used.
class MyKeyListener implements KeyAdapter
public void keyPressed (KeyEvent e )
char c = e . getKeyChar () ;
if (charList . contains(c))
charList .remove((Character) c) ;
System. out . println ( charList ) ;
} ...
MyKeyListener keyListener = new MyKeyListener () ;
This rewrite saves some space because we can choose which methods to override. After
the key listener is created, we need to register it with the event source (in our case this will
be a JFrame object). Here is an example of how one can do that.
JFrame frame = new JFrame () ;
frame . addKeyListener(keyListener ) ;
Search WWH ::

Custom Search