2011-05-03 89 views
0

我想創建一個名爲InputManager的類來處理鼠標事件。這要求mousePressed包含在InputManager類中。mousePressed可以在類中定義嗎?

像這樣

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

問題是,不能正常工作。 mousePressed()只在類外部時才起作用。

如何獲得這些功能很好地包含在一個類中?

回答

0

十分肯定,但是你有責任確保它被稱爲:

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); 

} 

0

試試這個

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()的結尾)。

0

做最簡單的方式,以便爲:

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

InputManager im = new InputManager(); 

void setup() { 
    // ... 
} 

void draw() { 
    // ... 
} 

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

這應該可以解決你在你的類變量範圍進行了任何問題。

注意:在該類中,甚至不必命名爲mousePressed,只要您在主mousePressed方法內調用它即可任意指定它。

相關問題