2017-03-07 108 views
0

Hello from java开发者,我在一个线程中创建了一个MouseListenerMouseAdapter来控制鼠标按下,释放和拖动动作的鼠标动作。每个动作都会执行特定的操作,但我无法将每个动作的每个MouseEvent e分配给一个变量。鼠标点击为布尔值

那么,如何处理这个问题呢?我还想知道方法参数MouseEvent e是否对每种方法都是特定的?

这里是我的代码:

Thread thread = new Thread() { 
    public void run() { 

    addMouseListener(new MouseAdapter() { 
     //@override deleted because i want to use e as a different action. 
     public void mouseaction(MouseEvent e) { 

      /* In here i want to control MouseEvent e action 
      (drag, pressed and released) and do specific things in with e event 
      and if e changes state should be changed in code during while(true) */ 

     } 
    } 
} 
+0

顺便说一句,您不需要单独的线程来添加鼠标侦听器。 –

回答

2

您可以通过调用方法getModifiersEx(),例如获得来自mouseEvent所有这些信息:

int eventType = e.getModifiersEx(); 
if (eventType & MOUSE_DRAGGED > 0) { 
    // Code to be executed when mouse is dragged 
} 

if (eventType & MOUSE_PRESSED > 0) { 
    // Code to be executed when mouse button is pressed 
} 
... 

注意,eventType是位字段,其中可以同时激活多个位。

+0

既然你在最后告诉它,你可以有多个修饰符,所以'else if'不是一个好主意,多个'if'最好确保测试每个案例 – AxelH

+0

@AxelH:对,修改了我的答案。 –

+0

@FrankPuffer int eventType = e.getModifiersEx();返回0为每个动作 – novice

0

我会解决这个问题:

我也想知道如果方法参数的MouseEvent e是具体到每一个方法?

每次Swing调用此方法时,都会生成一个新事件。您的@Override注释没有区别。

所以当用户点击某处时,会为其生成一个MouseEvent N°2556,并将该事件作为参数调用该方法。

当用户拖动鼠标时,会生成一个MouseEvent N°2557,并将该新事件作为参数再次调用该方法。


更广泛地说:所有那些MouseEvent将永远是不同的实例。它们也是不变的。

这意味着如果你想坚持一些信息为你的游戏循环看到,你需要将相关条件存储在某个字段的某个字段。而且你将无法从匿名类访问它,因为你无法处理它。这里是一个快速和肮脏的例子(动@ FrankPuffer的代码重用无耻):

public class MyMouseAdapter extends MouseAdpater { 
    public boolean isMousePressed = false; // This info is persisted here 
    public void mouseaction(MouseEvent e) { // This is only triggered upon user input 
     int eventType = e.getModifiersEx(); 
     if (eventType & MouseEvent.MOUSE_PRESSED) { 
      isMousePressed = true; 
     } 
     if (eventType & MouseEvent.MOUSE_RELEASED) { 
      isMousePressed = false; 
     } 
    } 
} 

public static void main(String[] argc){ 
    // Before the game loop: 
    MyMouseAdapter myAdapter = new MyMouseAdapter(); 
    jpanel.addMouseListener(myAdapter); 

    // In the game loop 
    while(true) { 
     if(myAdapter.isMousePressed) { // This info is available anytime now! 
       // Do something 
     } 
    } 
} 
+0

但是if(eventType&MouseEvent.MOUSE_PRESSED)是int并且编译器说它不能被转换。 – novice

1
//@override deleted because i want to use e as a different action. 
public void mouseaction(MouseEvent e) 

你不能只是弥补方法名。您需要实现侦听器的方法。您需要分别处理mousePressed,mouseReleased方法。对于mouseDragged,你需要实现MouseMotionListener。

阅读Swing教程Implementing Listener中的部分。你可以找到部分:

  1. 如何推行的MouseListener
  2. 如何推行的MouseMotionListener

其中都包含工作的例子。