Dave Drohan (SETU)

BACK NEXT

Mouse event methods

In some previous examples, 3.5 to 3.8 inclusive, we used the mouse system variables e.g. mousePressed.

In this step, you will re-write that code to use mouse event methods instead e.g. void mousePressed().

You will notice, this time, that we haven’t given you the reworked code to type in; have a go at making the code changes yourself and if you need some help, you can refer to your lecture notes (or download the solutions). And don’t worry if you have to refer to either the notes or the solutions, you are only three weeks into the course!

Example 3.5

Create a new Processing sketch in your workspace and call it Exercise_3_5_v2.

Cut and paste the following code into your sketchbook:

void setup() {
  size(100,100);
}

void draw() {
   background(0);
   stroke(255);
   fill(128);
   if (mousePressed){
       rect(45,45,34,34); 
   }
   else{
       ellipse(45,45,34,34);     
   }
}

Run the code so that you understand exactly what it does.

Rework the code so that it no longer tests the mousePressed variable but uses the void mousePressed() method instead.

Run your code. Does it work as you would expect?

Example 3.6

Create a new Processing sketch in your workspace and call it Exercise_3_6_v2.

Cut and paste the following code into your sketchbook:

void setup() {
  size(100,100);
}

void draw() {
  background(204);
  if (mousePressed == true)    
  {
       fill(255); // white
   } else {
       fill(0);     // black
   }
   rect(25, 25, 50, 50);
}

Run the code so that you understand exactly what it does.

Rework the code so that it no longer tests the mousePressed variable but uses the void mousePressed() method instead.

Run your code. Does it work as you would expect?

Example 3.7

Create a new Processing sketch in your workspace and call it Exercise_3_7_v2.

Cut and paste the following code into your sketchbook:

void setup() {
  size(100,100);
}

void draw() { 
   if (mousePressed){
       if (mouseButton == LEFT) 
            fill(0);      // black
       else if (mouseButton == RIGHT)
            fill(255);    // white
   }        
   else { 
       fill(126);     // gray
    }
    rect(25, 25, 50, 50);
}

Run the code so that you understand exactly what it does.

Rework the code so that it no longer tests the mouse system variable but uses the mouse event methods instead.

Run your code. Does it work as you would expect?

Example 3.8

Create a new Processing sketch in your workspace and call it Exercise_3_8_v2.

Cut and paste the following code into your sketchbook:

void setup() {
  size(500,400);
  background(0);
}

void draw() {
 
  if (mousePressed) {
    background(0);
  }

  stroke(255);
  fill(45,45,45);
  ellipse(mouseX, mouseY, 100, 100);
}

Run the code so that you understand exactly what it does.

Rework the code so that it no longer tests the mouse system variable but uses the mouse event methods instead.

Run your code. Does it work as you would expect?