Reset by pressing key

Hello,

I am trying to reset my canvas if pressing a key but cannot get it to work. Any ideas?

int boxsize = 80;
int cols, rows;
ArrayList<Box> boxes = new ArrayList<Box>();
Box active;

public enum Shape {
  TRIANGLE,
    ELLIPSE,
    RECT,
    RESET
}

void mouseClicked() {
  for (Box box : boxes) {
    int x = box.getX()*boxsize;
    int y = box.getY()*boxsize;
    if (mouseX > x && mouseX < (x + boxsize) && mouseY > y && mouseY < (y + boxsize)) {
      switch(box.getShape()) {
      case RESET:
        box.setShape(Shape.RECT);
        break;
      case RECT:
        box.setShape(Shape.TRIANGLE);
        break;
      case TRIANGLE:
        box.setShape(Shape.ELLIPSE);
        break;
      case ELLIPSE:
        box.setShape(Shape.RESET);

        break;
      }
    }
  }
}

void mouseDragged() {
  for (Box box : boxes) {
    int x = box.getX()*boxsize;
    int y = box.getY()*boxsize;
    if (mouseX > x && mouseX < (x + boxsize) && mouseY > y && mouseY < (y + boxsize)) {
      if (active != box) {
        switch(box.getShape()) {
        case RESET:
          box.setShape(Shape.RECT);
          active = box;
          break;
        case RECT:
          box.setShape(Shape.TRIANGLE);
          active = box;
          break;
        case TRIANGLE:
          box.setShape(Shape.ELLIPSE);
          active = box;
          break;
        case ELLIPSE:
          box.setShape(Shape.RESET);
          active = box;
          break;
        }
      }
    }
  }
}

void setup() {
  size(1300, 600);
  cols = width/boxsize;
  rows = height/boxsize;
  for (int i=0; i<cols; i++) {
    for (int j=0; j<rows; j++) {
      boxes.add(new Box(i, j, Shape.RESET));
    }
  }
}

void draw() {
  background(255);
  for (Box box : boxes) {
    int x = box.getX()*boxsize;
    int y = box.getY()*boxsize;
    fill(color(0));
    noStroke();
    switch(box.getShape()) {
    case RESET:
      fill(color(255));
      rect(x, y, boxsize, boxsize);
      break;
    case RECT:
      rect(x, y, boxsize, boxsize);
      break;
    case TRIANGLE:
      //triangle(x+(boxsize/2), y, x+boxsize, y+boxsize, x, boxsize);
      triangle(x, y+boxsize, x+(boxsize/2), y, x+boxsize, y+boxsize);
      break;
    case ELLIPSE:
      ellipse(x + (boxsize/2), y + (boxsize/2), boxsize, boxsize);
      break;
    }
  }
}```

You have background which is already good

You can say boxes.clear();

Or you can move the section of setup to a new function defineBoxes and call it from setup() and from keyPressed()

void keyPressed () {
     defineBoxes();
}
1 Like

Hey @Chrisir, thanks a lot! It helped me greatly!

1 Like