Handle (and consume) mouse events in classes

To my surprise, Processing doesn’t directly call back input events such as mousePressed(), keyReleased(), etc. :open_mouth:

But only these 2 input events: mouseEvent() & keyEvent(). :drooling_face:

So we can only use those 2 for registerMethod() as input events:

/**
 * RegisterMethod MouseEvent (v1.0)
 * GoToLoop (2020/Feb/10)
 *
 * https://Discourse.Processing.org/t/
 * handle-and-consume-mouse-events-in-classes/17689/4
 *
 * https://GitHub.com/processing/processing/wiki/
 * Library-Basics#when-drawing-or-code-that-manipulates-a-sketch-can-occur
 */

static final int INSTANCES = 3;
final SomeClass[] consumers = new SomeClass[INSTANCES];

void setup() {
  noLoop();
  for (int i = 0; i < INSTANCES; consumers[i] = new SomeClass(i++));
}

public class SomeClass {
  int val;

  SomeClass(final int num) {
    val = num;
    registerMethod("mouseEvent", this);
  }

  void mouseEvent(final MouseEvent evt) {
    if (evt.getAction() == MouseEvent.PRESS)  mousePressed();
  }

  void mousePressed() {
    print(val, TAB);
  }
}

Check out this wiki link below for more details on how to use those 2 input events: :face_with_monocle:

1 Like