Use Mouse-funktions in classes

I want to write a class that is able to use Mouse-funktions like mousePressed() but the funktion is not triggered in a class:

myClass c;

void setup() {
  size(500, 500);
  
  c = new myClass();
}

void draw() {
  c.update();
}


class myClass{
  void update() {
    
  }
  
  void mousePressed() {
    println("mouse was pressed at frame "+frameCount);
  }
}

Until now I solved the problem like this:

void mousePressed() {
  c.mousePressed();
}

is there a way that the class can also start the functions on its own?

Use registerMethod().

image

Example

Create a **public** void mouseEvent(){} method in your class and call p.registerMethod("mouseEvent", this); during the class object’s initialisation, where p is the parent PApplet.

2 Likes
myClass c;

void setup() {
  size(500, 500);

  c = new myClass(this);
}

void draw() {
  c.update();
}


public class myClass {
  myClass(PApplet p) {
    p.registerMethod("mouseEvent", this);
  }

  void update() {
  }

  void mousePressed() {
    println("mouse was pressed at frame "+frameCount);
  }

  public void mouseEvent(MouseEvent e) {
    if (e.getAction() == MouseEvent.PRESS) {
      println("mouse pressed at " + e.getX() + " " + e.getY());
    }
  }
}

it’s actually quite complicated :frowning:

3 Likes

For a small project I don’t know why making it so complicated.

Why not just calling the function through the mouseClicked() function?

myClass c;

void setup() {
  size(500, 500);

  c = new myClass(this);
}

void draw() {
  c.update();
}

void mouseClicked() {
  c.myEvent();
}

public class myClass {
  myClass(PApplet p) {
    p.registerMethod("mouseEvent", this);
  }

  void update() {
  }

  void myEvent() {
    println("mouse was pressed at frame "+frameCount);
  }
}

Tanks, it works cery well.

1 Like

I’m trying to make a class that specifies buttons and other things that are also automatically pressed. Since I will need this class more often, it is very cumbersome to write it down for each funktion.

btw you can omit the PApplet parameter in the constructor of myClass and just do registerMethod("mouseEvent", this);.

1 Like