Java Reference
In-Depth Information
WINDOW TITLE
event: key pressed
event listener: keyListener
event source
FIGURE 10.2: Example of key listener.
Note that a key listener can also be added to a panel. However, before doing so, call the
setFocusable(true) method inside the panel constructor. By default, a panel cannot get
the focus and only the component that has the focus is notified about key events. Figure 10.2
shows an example of how everything works. The window must have the focus because only
components that have the focus can listen for key strokes. A key listener is registered with
the window. Once a key is pressed, the window calls the keyPressed method of the key
listener and sends the event as a parameter. The key listener can extract the key that is
being pressed from the event and take appropriate action.
Here is the new version of the typing program, where we have made use of anonymous
local classes in order to shorten the code.
import java .awt. event . ;
import java . util . ;
import javax . swing . ;
import javax . swing .Timer;
public class TypingGame {
public static final int MAX COUNTER = 150;
public static final int MAX SIZE = 10;
public static final int INTERVAL = 200;
public static void main(String [] args)
{
JFrame frame = new JFrame () ;
final ArrayList < Character > charList = new ArrayList <> () ;
frame . addKeyListener( new KeyAdapter ()
{
public void keyPressed (KeyEvent e )
{
char c = e . getKeyChar () ;
if (charList . contains(c)) {
charList .remove((Character) c) ;
System. out . println ( charList ) ;
}
}
);
Timer t = new Time r ( INTERVAL, new ActionListener ()
{
int counter = 0;
public void actionPerformed(ActionEvent e)
{
charList .add(( char )( 'a' +( int ) ((Math . random()
26)))) ;
System. out . println ( charList ) ;
counter++;
if (counter ==MAXCOUNTER) {
System. out . println ( "You win!" );
 
Search WWH ::




Custom Search