CSI 3125, Preliminaries, page 1 Adapter Class
CSI 3125, Preliminaries, page 2 Adapter Class Java provides a special feature, called an adapter class, that can simplify the creation of event. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when want to receive and process only some of the events that are handled by a particular event listener interface. By extending one of the adapter classes and implementing only those events in which you are interested.
CSI 3125, Preliminaries, page 3 Adapter Class For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ). If you were interested in only mouse drag events, then simply extend MouseMotionAdapter and implement mouseDragged( ). commonly used adapter classes in java.awt.event
CSI 3125, Preliminaries, page 4 Adapter Class Listener InterfaceAdapter Class ComponentListenerComponentAdapter ContainerListenerContainerAdapter FocousListenerFocousAdapter KeyListenerKeyAdapter MouseListenerMouseAdapter MouseMotionListenerMouseMotionAdapter WindowListenerWindowAdapter
CSI 3125, Preliminaries, page 5 MouseAdapter Class prog import java.applet.*; import java.awt.event.*; /* */ public class M3 extends Applet { MyMouseAdapter k=new MyMouseAdapter(); public void init() { addMouseListener(k); } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed”); }
CSI 3125, Preliminaries, page 6 MouseAdapter Class prog (Inner Class) import java.applet.*; import java.awt.event.*; /* */ public class M3 extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed”); } } ); }
CSI 3125, Preliminaries, page 7 MouseAdapter Class to draw rect Prog (Inner Class) import java.applet.*; import java.awt.*; import java.awt.event.*; /* */ public class M3 extends Applet { int X1,Y1,X2,Y2; public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { X1 = me.getX(); Y1 = me.getY(); } public void mouseReleased(MouseEvent me) { X2=me.getX();Y2=me.getY(); repaint(); } }); } public void paint(Graphics g) {g.drawRect(X1, Y1, X2-X1, Y2-Y1); } }
CSI 3125, Preliminaries, page 8 WindowAdapter Class (Inner class) Prog public class w1 extends java.awt.Frame { public w1() { addWindowListener( new java.awt.event.WindowAdapter() { public void windowClosing( java.awt.event.WindowEvent e ) { System.out.println( "good bye" ); } ); } public static void main( String[] args ) { w1 foo = new w1() ; foo.setSize( 200, 200 ); foo.setVisible( true ); }
CSI 3125, Preliminaries, page 9 Adapter Class
CSI 3125, Preliminaries, page 10 Adapter Class