Event Adapters

There are some event listeners that have multiple methods to implement. That is some of the listener interfaces contain more than one method.

Event Adapters

There are some event listeners that have multiple methods to implement. That is some of the listener interfaces contain more than one method.

Event Adapters

Event Adapters

     

There are some event listeners that have multiple methods to implement. That is some of the listener interfaces contain more than one method. For instance, the MouseListener interface contains five methods such as mouseClicked, mousePressed, mouseReleased etc. If you want to use only one method out of these then also you will have to implement all of them. Thus, the methods which you do not want to care about can have empty bodies. To avoid such thing, we have adapter class. 

Adapter classes help us in avoiding the implementation of the empty method bodies. Generally an adapter class is there for each listener interface having more than one method. For instance, the MouseAdapter class implements the MouseListener interface. An adapter class can be used by creating a subclass of it and then overriding the methods which are of use only. Hence avoiding the implementation of all the methods of the listener interface. The following example shows the implementation of a listener interface directly. 

public class MyClass implements MouseListener {
...
someObject.addMouseListener(this);
...

/* Empty method definition. */
public void mouseEntered(MouseEvent e) {
}

/* Empty method definition. */
public void mouseExited(MouseEvent e) {
}

/* Empty method definition. */
public void mousePressed(MouseEvent e) {
}

}
}