/* * File: mEventApplet.java * * MouseEvents and movable objects */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class mEventApplet extends Applet implements MouseListener, MouseMotionListener { // Instance variables: private int numObj = 3; // number of movable objects private mPoint object[]; // array of movable objects private Image buffer; // image object for double buffering private Graphics gOffScreen; // graphics object for double buffering // Mouse handling variables: private int current = -1; private int hit = -1; private int xoffset = 0; private int yoffset = 0; // Colors: private Color objColor = Color.cyan; private Color objColorSelect = Color.red; private Color bgColor = Color.black; private Color fgColor = Color.white; public void init() { setBackground( bgColor ); setForeground( fgColor ); // Instantiate object array: object = new mPoint[ numObj ]; // Instantiate a rectangle: object[0] = new mRectangle( 10, 10, 100, 100 ); object[0].setColor( objColor ); // Instantiate a circle: object[1] = new mOval( 200, 10, 100, 100 ); object[1].setColor( objColor ); // Instantiate a triangle: object[2] = new mTriangle( 10, 200, 100, 100 ); object[2].setColor( objColor ); // Create an off-screen image for double buffering: buffer = createImage( getSize().width, getSize().height ); // Get off-screen graphics context: gOffScreen = buffer.getGraphics(); // Register the applet to listen for ALL mouse events: addMouseListener( this ); addMouseMotionListener( this ); } // Override java.awt.Component.update: public void update( Graphics g ) { // Fill background: gOffScreen.setColor( getBackground() ); gOffScreen.fillRect( 1, 1, getSize().width - 2, getSize().height - 2 ); // Draw boundary: gOffScreen.setColor( getForeground() ); gOffScreen.drawRect( 0, 0, getSize().width - 1, getSize().height - 1 ); paint( gOffScreen ); // Draw the buffer in the applet window: g.drawImage( buffer, 0, 0, this ); } // Override java.awt.Component.paint: public void paint( Graphics g ) { // Paint each object: for ( int i = 0; i < numObj; i++ ) { object[i].paint(g); } } // MouseMotionListener event handlers: public void mouseMoved( MouseEvent e ) { hit = -1; for ( int i = 0; i < numObj; i++ ) { if ( object[i].isInside( e.getX(), e.getY() ) ) { hit = i; break; } } for ( int i = 0; i < numObj; i++ ) { object[i].setColor( (i == hit) ? objColorSelect : objColor ); } repaint(); } public void mouseDragged( MouseEvent e ) { if ( current != -1 ) { int x = e.getX() + xoffset; int y = e.getY() + yoffset; object[current].setPoint( x, y ); repaint(); } } // MouseListener event handlers: public void mousePressed( MouseEvent e ) { current = hit; if ( current != -1 ) { xoffset = object[current].getX() - e.getX(); yoffset = object[current].getY() - e.getY(); } } public void mouseReleased( MouseEvent e ) { current = -1; } public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } }