The Coder's Handbook   

Mouseover and Clicks

PUTTING IT ALL TOGETHER

We've learned how to detect if the user clicked the mouse, and which mouse button they have clicked.  We also know how to find the mouse's location. But often we really care about how the mouse's position interacts with something we're drawing on the screen.  


For example:

MOUSEOVER (CIRCLES)

Detecting If You Are Over a Circle

We can write a method called isMouseOver() that returns a true when the mouse is over our drawn circle and false otherwise.


Consider the example to the right:

int xPos = 50;

int yPos = 50;

int radius = 20;


void draw()

{   

if(isMouseOver())

{

   fill(255, 0, 0);

}

else

{

   fill(255, 255, 255);

}
   

   ellipse(xPos, yPos, radius * 2, radius * 2);

}


boolean isMouseOver()

{

if(dist(mouseX, mouseY, xPos, yPos) < radius)

  {

   return true;
  }

else
  {

    return false;
  } 

}

MOUSEOVER (RECTANGLES)

Detecting If You Are Over a Rectangle

We can use the same technique for rectangles.  This would work for both drawn rectangles and for images, since all images are rectangles.


Consider the example to the right:

int xPos = 50;

int yPos = 50;

int w = 100;

int h = 20;


void draw()

{   

if(isMouseOver())

{

   fill(255, 0, 0);

}

else

{

   fill(255, 255, 255);

}

   rect(xPos, yPos, w, h);

}


boolean isMouseOver()

{

if(mouseX > xPos &&     // > Left 

   mouseX < xPos + w &&   // > Right 

   mouseY > yPos && // > Top 

   mouseY < yPos + h) // < Bottom

  {

   return true;

}

else
  {

    return false;
  } 

}

REVIEW: POLLING vs. EVENTS

Using mousePressed

This is an input strategy called polling.  At any point in your program, at any time, you can simply ask Processing, "Hey, is the mouse down?"  and respond accordingly.


This is great in situations where:

Using void mousePressed()

This is an input strategy based on responding to an event.  Processing has a method called void mousePressed() which is called automatically every time you fully click-and-release the mouse. 


This is great in situations where:

For more detailed information and examples, look at the Coder's Handbook entry on Mouse and Keyboard

CLICKING WITH MOUSEPRESSED METHOD

Clicking A Rectangle

We can use the mousePressed method which is automatically called when the mouse is clicked.  Then, simply check if the mouse is over the destination then cause some sort of change in your program.


The example to the right expands on the mouseOver code we used previously.  In this case, we're moving the rectangle to a random location and giving the user a point.

int score = 0;


void mousePressed()

{   

if(isMouseOver())

{

   xPos = random(width);

   yPos = random(height);

   score++;

}

}

RESOURCES