Mouse-listener that stops a block from executing when the mouse is released

301 Views Asked by At

In Java, I need to integrate a mouse Listener that moves a motor. However here is the catch, there is no stop function. Thereby, the mousepressed should move the motor, while the mouseReleased should stop it, without actually sending a stop command but rather by stopping the mouse pressed block from executing. Any ideas on how this can be implemented? And is it possible to repeat the command under mousePressed as long as the mouse is pressed? The following code is to illustrate my current program, which uses a stop function, which i would rather avoid.

    n2Button.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                try {
                    //                        moveUp();
                    session.motion(0, 0, -500);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }

        public void mouseReleased(MouseEvent e) {
            if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                try {
                    session.stop();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });
1

There are 1 best solutions below

5
J J On

You rather want to have mouse motion listener [Example][1] [1]: https://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html And i also do not see the problem to have session.stop(); only the movement function i guess must be executed in another thread