2011-05-03 6 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, INT Y); " 인터페이스에서 "p5ec.mousePressed (mouseX, mouseY);"를 호출하면됩니다. 스케치 본문에서는 지역 변수가 아닌 전역 변수에 의존하는 것이 코드가 동시성 버그를 일으키는 경향이 있기 때문입니다. 당신이 PApplet에 InputManger 된 MouseEvent를 등록하면

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... 
     } 
    } 
} 

당신이 그것을 호출 할 필요는 없습니다 그것은 호출됩니다 : InputManager 클래스에

InputManager im; 

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

} 

을 : 주 스케치에 을 :

0

이 시도 각 루프 (draw()의 끝에서).

0

가장 쉬운 방법은 이렇게 될 것이다 :

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

InputManager im = new InputManager(); 

void setup() { 
    // ... 
} 

void draw() { 
    // ... 
} 

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

이것은 당신이 당신의 클래스 변수 범위 지정으로 필요 된 모든 문제를 해결해야한다.

참고 : 클래스에서 mousePressed라는 이름을 지정할 필요조차 없습니다. 기본 mousePressed 메서드 내에서 호출하는 한 원하는 이름을 지정할 수 있습니다.

관련 문제