// Fig. 11.5: SelfContainedCanvas.java // A self-contained Canvas class that // handles its own mouse events. package com.deitel.jhtp2.ch11; import java.awt.*; import java.awt.event.*; public class SelfContainedCanvas extends Canvas implements MouseListener, MouseMotionListener { private int x1, y1, x2, y2; public SelfContainedCanvas() { addMouseListener( this ); addMouseMotionListener( this ); } public void paint( Graphics g ) { int x, y, width, height; // determine upper-left corner of bounding rectangle x = Math.min( x1, x2 ); y = Math.min( y1, y2 ); // determine width and height of bounding rectangle width = Math.abs( x1 - x2 ); height = Math.abs( y1 - y2 ); g.drawOval( x, y, width, height ); } public void mousePressed( MouseEvent e ) { x1 = e.getX(); y1 = e.getY(); } public void mouseReleased( MouseEvent e ) { x2 = e.getX(); y2 = e.getY(); repaint(); } public void mouseDragged( MouseEvent e ) { x2 = e.getX(); y2 = e.getY(); repaint(); } // These methods not used but must be defined because // we implement MouseListener and MouseMotionListener. public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mouseMoved( MouseEvent e ) { } }