javaswingmouseeventmouselistenermousemotionlistener

Register MouseListener and MouseMotionListener simultaneously


I am trying to write a Mouse class (implementing MouseListener and MouseMotionListener) containing mousePressed() and mouseMoved(). I want to be able to detect mouse motion while the mouse is down. I can detect each separately, but not at the same time. For example:

import javax.swing.*;
import java.awt.event.*;
public class Test extends JPanel {
  public Test() {
     Mouse m = new Mouse();
     addMouseListener(m);
     addMouseMotionListener(m);
  }
  class Mouse implements MouseListener, MouseMotionListener{
     public void mousePressed(MouseEvent e) {
        System.out.println("Pressed");
     }
     public void mouseMoved(MouseEvent e) {
        System.out.println("Moved");
     }
     public void mouseDragged(MouseEvent e) {}
     public void mouseClicked(MouseEvent e) {}
     public void mouseEntered(MouseEvent e) {}
     public void mouseExited(MouseEvent e) {}
     public void mouseReleased(MouseEvent e) {}
   }
   public static void main(String[] args) {
     JFrame frame = new JFrame();
     frame.setSize(500, 500);
     frame.setLocationRelativeTo(null);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setContentPane(new Test());
     frame.setVisible(true);
   }
}

As you should see, "Pressed" and "Moved" are both printed out, but once the mouse is pressed, "Moved" is not printed until the mouse is released. How would I make it so that it would do that?


Solution

  • From the Java API:

    void mouseDragged(MouseEvent e)

    Invoked when a mouse button is pressed on a component and then dragged.

    void mouseMoved(MouseEvent e)

    Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

    mouseMoved events are only fired when no buttons are pressed.