我想创建一个名为InputManager的类来处理鼠标事件。这要求mousePressed包含在InputManager类中。mousePressed可以在类中定义吗?
像这样
class InputManager{
void mousePressed(){
print(hit);
}
}
问题是,不能正常工作。 mousePressed()只在类外部时才起作用。
如何获得这些功能很好地包含在一个类中?
我想创建一个名为InputManager的类来处理鼠标事件。这要求mousePressed包含在InputManager类中。mousePressed可以在类中定义吗?
像这样
class InputManager{
void mousePressed(){
print(hit);
}
}
问题是,不能正常工作。 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();
}
}
我会亲自做有点收紧也通过传递事件变量明确,所以“无效的mousePressed(INT X,诠释ÿ );”在界面中,然后调用“p5ec.mousePressed(mouseX,mouseY);”在草图主体中,仅仅因为依赖全局变量而不是局部变量会使您的代码容易出现并发错误。在主要草图 :在输入管理类
InputManager im;
void setup() {
im = new InputManager(this);
registerMethod("mouseEvent", im);
}
:
试试这个
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的MouseEvent你不需要调用它,它会被称为每个循环(在draw()的结尾)。
做最简单的方式,以便为:
class InputManager{
void mousePressed(){
print(hit);
}
}
InputManager im = new InputManager();
void setup() {
// ...
}
void draw() {
// ...
}
void mousePressed() {
im.mousePressed();
}
这应该可以解决你在你的类变量范围进行了任何问题。
注意:在该类中,甚至不必命名为mousePressed,只要您在主mousePressed方法内调用它即可任意指定它。