鼠标单击以布尔

时间:2017-03-07 09:31:23

标签: java swing

你好新手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) */

        }
    }
}

3 个答案:

答案 0 :(得分:2)

您可以通过调用方法mouseEventgetModifiersEx()获取所有这些信息,例如:

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是一个位字段,可以同时激活多个位。

答案 1 :(得分:1)

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

您不能仅仅编制方法名称。您需要实现侦听器的方法。您需要单独处理mousePressed,mouseReleased方法。对于mouseDragged,您需要实现MouseMotionListener。

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

  1. 如何实施MouseListener
  2. 如何实施MouseMotionListener
  3. 都包含工作示例。

答案 2 :(得分: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
         }
    }
}