1

So I have a ON-OFF button that draws a circle. The trouble I am encountering is that the ON OFF states are random depending on how long I press the button. I guess this is due to the draw() function which also loops my button function in time with framerate. What I want is for the button to turn on when pressed once and turn off when pressed again irrespective of how long the button is pressed. Here is the code.

else if (circle4.pressed()) {
  println("button 4 is pressed");

  if(drawCirclesPrimary){
  drawCirclesPrimary = false;
  }
  else{
  drawCirclesPrimary = true;
  }
  println("drawCirclesPrimary"+drawCirclesPrimary);
}
Kevin Workman
  • 39,413
  • 8
  • 61
  • 94
allgored
  • 25
  • 1
  • 6

2 Answers2

1

I would suggest looking at the Buttons tutorial on processing.org. The following code is a subset of what is contained in the tutorial (you will need to review all the code in the tutorial, however). Comments are mine.

void setup() { 
  // Create instances of your button(s)
}

void draw() { 
  // Draw buttons, update cursor position, check if buttons have been clicked.
}

// Provides the overRect() method (among others).
class Button
{
    // If the cursor is placed within the footprint of the button, return true.
    boolean overRect(int x, int y, int width, int height) 
    {
      if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) {
        return true;
      } 
      else {
        return false;
      }
    }
}


class RectButton extends Button
{  
   // Create a rectangle button with these size/color attributes.
   RectButton(int ix, int iy, int isize, color icolor, color ihighlight) 
   {
      x = ix;
      y = iy;
      size = isize;
      basecolor = icolor;
      highlightcolor = ihighlight;
      currentcolor = basecolor;
   }

   // Determines whether the cursor is over the button.
   boolean over() 
   {
      if( overRect(x, y, size, size) ) {
        over = true;
        return true;
      } 
      else {
        over = false;
        return false;
      }
   }

   // Draws the rectangle button into your sketch.
   void display() 
   {
      stroke(255);
      fill(currentcolor);
      rect(x, y, size, size);
   }
}
gary
  • 4,131
  • 2
  • 29
  • 56
0

This thread has some example code for drawing an object only while a key is pressed. That's pretty similar to what you want.

Instead of keyPressed and keyReleased, you can use mouseClicked. which is called once after a mouse button has been pressed and then released. Use a boolean variable to store the on/off state. Inside of mouseClicked, toggle the value of that boolean variable.

jlstrecker
  • 4,643
  • 1
  • 42
  • 57