// File: DrawCanvas.java import java.awt.*; import java.awt.event.*; import java.applet.*; public class DrawCanvas extends Canvas { Graphics g; String curMode="Rect"; mPoint curObj; public boolean fill=true; mPoint objList[]=new mPoint[100]; int index=0; public DrawCanvas() { setBackground(Color.blue); setForeground(Color.yellow); // Notice the construction of two listener objects, ourMouseListener // and ourMotionListener. Both are constructed from the class // definitions, called anonymous classes. // "You should consider using an anonymous class instead of // [a top level class or] a local class if: // . The class has a very short body. // . Only one instance of the class is needed. // . The class is used right after it is defined. // . The name of the class does not make your code any easier to understand." // [Java in a Nutshell, pg. 119] // We define our version of mouse adapters here // because we will not use all of the MouseListener methods. // MouseListener is an interface and all of its methods are defined abstract. // This forces us to overwrite all the methods even though we do not need some. // To overcome this problem, adapter classes are developed. These are // classes implementing interfaces with empty method bodies. Hence, we only // overwrite those methods that we need. // In this case, we need mousePressed and mouseReleased. MouseListener ourMouseListener = new MouseAdapter() { // from MouseAdapter public void mousePressed(MouseEvent e) { int x=e.getX(); int y=e.getY(); if (curMode.equals("Rect")) curObj=new mRectangle(x, y, x, y); else if (curMode.equals("Circ")) curObj=new mCircle(x, y, x, y); else if (curMode.equals("Line")) curObj=new mLine(x, y, x+1, y+1); else if (curMode.equals("Round")) curObj=new mRound(x, y, x, y); } // from MouseAdapter public void mouseReleased(MouseEvent e) { g=getGraphics(); g.setPaintMode(); curObj.setEnds(e.getX(), e.getY()); curObj.setFill(fill); objList[index++]=curObj; curObj.draw(g); if(index>=100) index=100; } }; // We also need mouseDragged from MouseMotionListener. MouseMotionListener ourMotionListener = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { g=getGraphics(); g.setXORMode(Color.black); curObj.draw(g); curObj.setEnds(e.getX(), e.getY()); curObj.draw(g); } }; addMouseListener( ourMouseListener ); addMouseMotionListener( ourMotionListener ); } public void setDrawMode(String s) { if(s.equals("Clear")) { index=0; repaint(); } else if(s.equals("Redraw")) repaint(); else curMode=s; } public void paint(Graphics g) { g.setColor(Color.yellow); super.paint(g); for(int i=0; i