Adapter Classes
Java provides a special feature, called an adapter class, which will simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all
methods in an occasion listener interface. Adapter classes are useful once you want to receive and process just some of the events that are handled by a specific event listener interface.
You can define a replacement class to act as an occasion listener by extending one among the adapter classes and implementing only those events during which you’re interested.
java.awt.event Adapter classes
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
int x=m.getX();
int y=m.getY();
t1.setText(x+","+y);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Anonymous Inner Class
import java.awt.*;
import java.awt.event.*;
class MouseAnonymousDemo
{
Label l1;
TextField t1;
Frame f;
MouseAnonymousDemo()
{
f=new Frame();
f.setTitle("My First Frame");
f.setSize(500,500);
f.setVisible(true);
f.setLayout(new FlowLayout());
l1=new Label("Current Mouse Clicked Position");
t1=new TextField(10);
f.add(l1);
f.add(t1);
f.addMouseListener( new MouseAdapter() {
public void mouseClicked (MouseEvent m)
{
int x=m.getX();
int y=m.getY();
t1.setText(x+","+y);
}
});
}
}
class MouseAnonymousFrame
{
public static void main(String arg[])
{
MouseAnonymousDemo m =new MouseAnonymousDemo();
}
}