//  Scott DeRuiter        3/6/2003
//  Chase.java
//  Chases a ball around, implementing a MouseMotionListener in
//  a Swing Applet.
//	3/13/2013 Greenstein: changed from applet to JFrame

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Chase implements MouseMotionListener 
{

	private int ballx, bally, xpos, ypos, changex, changey;
	private boolean moveball, caughtit;
   
	private JFrame frame;
	private MyPanel canvas;

	public Chase ()    
	{
		xpos = ypos = changex = changey = 0;
		ballx = bally = 200;
		moveball = caughtit = false;
	}
   
	public static void main(String[] args) 
	{
		Chase ch = new Chase();
		ch.Run();
	}

	public void Run() 
	{
		// Create a frame to hold everything
		frame = new JFrame ("Chase");
		frame.setSize(500, 500);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//frame.setBackground(Color.black);	// only needed if frame is larger than panel
		
		// Define panel to draw on
		canvas = new MyPanel();		// create a panel to draw on
		canvas.setBackground(Color.lightGray);
		canvas.addMouseMotionListener(this);	// connects the addMouseMotionListener to the panel window
		
		// Put frame together
		frame.getContentPane().add(canvas);	// puts panel on frame
		frame.setVisible(true);
	}
   
	class MyPanel extends JPanel 
	{

		public void paintComponent(Graphics g) 
		{
      
			super.paintComponent(g);

			g.setColor ( Color.blue );
			g.fillOval ( ballx - 10, bally - 10, 20, 20 );

			while ( moveball )    
			{
				g.setColor ( Color.lightGray );
				g.fillOval ( ballx - 10, bally - 10, 20, 20 );
				changex = (int)( Math.random() * 31 ) - 15;
				changey = (int)( Math.random() * 31 ) - 15;
				ballx += changex;
				bally += changey;
				if ( ballx > 380 )
					ballx = 370;
				if ( ballx < 20 )
					ballx = 30;
				if ( bally > 380 )
					bally = 370;
				if ( bally < 20 )
					bally = 30;
				if ( caughtit )   
				{
					g.setColor ( Color.red );
					g.drawString ( "OOOHH, YOU GOT ME!!!", 20, 20 );
				}
				else
					g.setColor ( Color.blue );
				g.fillOval ( ballx - 10, bally - 10, 20, 20 );
				if ( Math.abs ( xpos - ballx ) > 30  || Math.abs ( ypos - bally ) > 30 )
					moveball = false;
			}
		caughtit = false;
		}

		public void mouseMoved ( MouseEvent e )   
		{   
			xpos = e.getX();
			ypos = e.getY();
			if ( Math.abs ( xpos - ballx ) < 10 && Math.abs ( ypos - bally ) < 10 )  
			{
				caughtit = true;
				canvas.repaint();
			}
			if ( Math.abs ( xpos - ballx ) < 35 && Math.abs ( ypos - bally ) < 35 )   
			{
				moveball = true;
				canvas.repaint();
			}
		}

	public void mouseDragged ( MouseEvent e )    {}
}

Back to Lesson 25 Examples

Back to Java Main Page