Java Code
/**
* Program that moves a button whenever the mouse gets near it.
* Shows example of MouseMotionListener events, null layout manager
* Date Mar 23, 2005
* @author : E.S.Boese
* E-id : sugar
* Course : CS150
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
// need to listen for mouseMoved events
public class Annoying extends JApplet implements MouseMotionListener
{
JButton winner = new JButton( "Click me and win a million" );
// need a Random object to randomly select a new x and y coordinates
// when we move the button to a new location
Random random = new Random( );
// Rectangle object that determines the x and y coordinates
// that trigger a move of the button.
// The coordinates are 10 pixels bigger than the actual button,
// such that if the mouse gets within 10 pixels of the button, the button
// will move
Rectangle rectangle = new Rectangle( );
public void init( )
{
// null layout so we can place the button in an exact location
setLayout( null );
// resize the applet to be 500 wide by 500 height pixels
resize( 500,500 );
// since we're using the null layout, we have to set the bounds on our
// button. x and y coordinates 100,200, width of 200 and height of 20
winner.setBounds(100,200,200,20);
// rectangle holds the buffer area, 10 pixels bigger than than the button
// records the x and y coordinates 90,190, width 220 and height 40
rectangle.setBounds( 90,190,220,40); // "too close" boundary
// listen for mouse movements on the applet
addMouseMotionListener(this);
// add button to applet
add(winner);
}
public void mouseMoved( MouseEvent me ) // required method to write
{
int x = me.getX( ); // get x coordinate of the mouse location
int y = me.getY( ); // get y coordinate of the mouse location
if( rectangle.contains( x, y ) ) // method returns true if x,y inside rectangle
{
// move the button to a new spot.
// to make sure it doesn't go off screen, the max x is 300
winner.setLocation( random.nextInt(300), random.nextInt(490) );
// reset the boundary for the rectangle, such that it's 10 pixels
// buffer from the new location of the button
rectangle.setBounds( winner.getX( )-10, winner.getY( )-10,
winner.getWidth( )+20, winner.getHeight( )+20 );
}
}
public void mouseDragged( MouseEvent me ) // required method to write
{ // leave it blank since we don't want to use it
}
}
Back to Code Examples
©2006-
by E.S.Boese. All Rights Reserved