Processing 可以在类中定义mousePressed吗?

Processing 可以在类中定义mousePressed吗?,processing,Processing,我试图创建一个名为InputManager的类来处理鼠标事件。这要求在InputManager类中包含mousePressed 像这样 类输入管理器{ void mousePressed(){ 打印(点击); } } 问题是,这行不通。mousePressed()似乎只有在类外时才起作用 如何将这些函数很好地包含在类中?当然可以,但您有责任确保调用它: interface P5EventClass { void mousePressed(); void mouseMoved();

我试图创建一个名为InputManager的类来处理鼠标事件。这要求在InputManager类中包含mousePressed

像这样

类输入管理器{
void mousePressed(){
打印(点击);
}
}
问题是,这行不通。mousePressed()似乎只有在类外时才起作用


如何将这些函数很好地包含在类中?

当然可以,但您有责任确保调用它:

interface P5EventClass {
  void mousePressed();
  void mouseMoved();
  // ...
}

class InputManager implements P5EventClass {
  // we MUST implement mousePressed, and any other interface method
  void mousePressed() {
    // do things here
  }
}

// we're going to hand off all events to things in this list
ArrayList<P5EventClass> eventlisteners = new ArrayList<P5EventClass>();

void setup() {
  // bind at least one input manager, but maybe more later on.
  eventlisteners.add(new InputManager());
}

void draw() {
  // ...
}

void mousePressed() {
  // instead of handling input globally, we let
  // the event handling obejct(s) take care of it
  for(P5EventClass p5ec: eventlisteners) {
   p5ec.mousePressed();
  }
}
接口类{
void mousePressed();
void mouseMoved();
// ...
}
类InputManager实现P5EventClass{
//我们必须实现mousePressed和任何其他接口方法
void mousePressed(){
//在这里做事
}
}
//我们将把所有事件都交给列表中的内容
ArrayList eventlisteners=新的ArrayList();
无效设置(){
//至少绑定一个输入管理器,但以后可能会绑定更多。
添加(新的InputManager());
}
作废提款(){
// ...
}
void mousePressed(){
//我们不再全局处理输入,而是让
//事件处理obejct会处理它
for(P5EventClass p5ec:eventlisteners){
p5ec.鼠标按下();
}
}
我个人会通过显式地传递事件变量使其更紧凑,因此在接口中“void mousePressed(int x,int y);”,然后在草图主体中调用“p5ec.mousePressed(mouseX,mouseY);”,这仅仅是因为依赖全局变量而不是局部变量会使代码容易出现并发错误

试试这个:

在主草图中:

InputManager im;

void setup() {
im = new InputManager(this);
registerMethod("mouseEvent", im);

}
在InputManager类中:

class InputManager {
    void mousePressed(MouseEvent e) { 
         // mousepressed handling code here... 
    }

    void mouseEvent(MouseEvent e) {
       switch(e.getAction()) {
          case (MouseEvent.PRESS) : 
               mousePressed();
               break;
          case (MouseEvent.CLICK) :
               mouseClicked();
               break;
          // other mouse events cases here...
       }
    }
}

在PApplet中注册InputManger MouseeEvent后,您无需调用它,它将在draw()结束时调用每个循环。

最简单的方法是:

class InputManager{
    void mousePressed(){
       print(hit);
    }
}

InputManager im = new InputManager();

void setup() {
   // ...
}

void draw() {
   // ...
}

void mousePressed() {
   im.mousePressed();
}
这将解决您在类中使用变量作用域时遇到的任何问题

注意:在类中,它甚至不必命名为mousePressed,只要在主mousePressed方法中调用它,就可以随意命名它