JaVa
   

Adapter Classes

The adapter classes implement the corresponding listener interfaces and define empty methods for you, thus the adapter class can be extended instead and only the methods required need to be overridden. The adapter classes that we are interested in are KeyAdapter (implements KeyListener), MouseAdapter (implements MouseListener), and MouseMotionAdapter (implements MouseMotionListener). These adapter classes are found in the package java.awt.event. If you prefer to combine the two mouse listener classes using MouseInputListener mentioned earlier, it has an associated adapter class: javax.swing.event.MouseInputAdapter. The adapter classes are used for added convenience; for example, for the SimpleKeyboard example, we could have added a nested class called MyKeyListener that extended the KeyAdapter class instead of implementing the KeyListener interface as follows:

public class MyKeyListener extends KeyAdapter
{
 public void keyPressed(KeyEvent e)
 {
 lastKeyEvent = e;
 repaint();
 } }


MyKeyListener extends the KeyAdapter class, which implements empty KeyListener methods, so we only need to override the ones that we require. You could then add a key listener to the main applet in the init method of SimpleKeyboard, as follows:

addKeyListener(new MyKeyListener());


With this method, the main applet class would no longer need to implement the KeyListener interface and define the three methods itself. However, do not let this added convenience put you off using the interface listeners. The advantage of using interfaces over extending classes is that you can have a class that implements, say, the KeyListener and the MouseListener or as many as you need, whereas you could not have a class that extended both the KeyAdapter and MouseAdapter, as Java does not support multiple inheritance.

TipĀ 

When using the adapter classes, remember to name the overridden methods correctly. Otherwise, you will not override them at all; you will simply be declaring a new method. This generally occurs when starting the method name with a capital letter (e.g., KeyPressed instead of keyPressed). Another reason it is better to use the interfaces is because the debugger will look for these methods and alert you if one is missing (or incorrectly spelled as the case may be).

However, arguably the neatest way to add a key listener is by defining a class "on the fly." We saw this in the previous chapter with the WindowListener, where we handled the closing of a window. With this method, you can simply do the following in the init method, for example.

addKeyListener(new KeyAdapter()
{
 public void keyPressed(KeyEvent e)
 {
 lastKeyEvent = e;
 repaint();
 }
});


Here we define our method for a new instance of KeyAdapter, as we define it. Though this method might seem quite unconventional to you if you're new to it, it's perfectly feasible and should grow on you.

JaVa
   
Comments