Search code examples
javaprocessingkeypresserase

Implementing an erase button in Processing


I have created an erase button in Processing with controlP5 library. The purpose of the erase button is, to erase when something is drawn with the mouse (when erase button is clicked). Similar to the paint program.

Thank you very much in advance!

Code for erase Button function:

**boolean erase = false;
void setup(){
}
void draw(){
void keyPressed(){ //there is an error in this line (error on void)
  if (keyPressed == true && erase == true) {
    
      background(255);
  }
}
}**

Solution

  • The keyPressed should be outside of the draw function. Also, the codeblock within the keyPressed function will execute only if a key is pressed, so you don't have to check it yourself.

    boolean erase = false;
    
    void setup(){
    }
    
    void draw(){
    }
    
    void keyPressed(){ 
      if (erase) {
          background(255);
      }
    }
    

    If you wanted to check that a key is pressed within the draw function then you can use the keyPressed boolean system variable.

    void draw(){
      if (keyPressed && erase) {
          background(255);
      }
    }
    

    Also, if you wanted a specific key to be pressed, you can use the key keyword.

    void keyPressed(){ 
      if (key == 'e' && erase) {
          background(255);
      }
    }