Java Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEyes extends JApplet implements MouseMotionListener
{
int mouseX, mouseY; // track current location of mouse
public void init( )
{
addMouseMotionListener( this );
}
public void paint( Graphics g )
{
g.clearRect( 0,0,getWidth( ),getHeight( ) );
int eyeWidth = 40;
int eyeHeight = 80;
g.setColor( Color.WHITE ); // color the whites of the eyes
g.fillOval( 0,0,eyeWidth,eyeHeight );
g.fillOval( eyeWidth,0, eyeWidth, eyeHeight );
g.setColor( Color.BLACK ); // draw outline
g.drawOval( 0,0, eyeWidth, eyeHeight ); // left eye
g.drawOval( 1,1, eyeWidth-2, eyeHeight-2 );
g.drawOval( eyeWidth,0, eyeWidth, eyeHeight ); // right eye
g.drawOval( eyeWidth+1,1, eyeWidth-2, eyeHeight-2);
// eyes, x,y as percent of where mouse is
int eyeX = (mouseX * 100 / getWidth( )) * eyeWidth / 100; // eyeball
int eyeY = (mouseY * 100 / getHeight( )) * eyeHeight / 100;
g.fillOval( eyeX, eyeY, 10,10 );
g.fillOval( eyeX+eyeWidth, eyeY, 10,10);
}
public void mouseMoved( MouseEvent me ) // track current location of mouse
{
mouseX = me.getX();
mouseY = me.getY();
repaint( );
}
public void mouseDragged( MouseEvent me ) { }
}
Back to Code Examples
©2006-
by E.S.Boese. All Rights Reserved