javaswingjpanelmouselistenermousemotionlistener

Implementing MouseMotionListener in JPanel


Continuing on from this question, I'm implementing a MouseMotionListener in my JPanel so that I can track mouse events to pass down to the objects contained within.

This didn't work, so I implemented a completely clean JPanel (that has none of the other stuff my game panel has) with a MouseMotionListener and that still didn't work. It's just set up in a very simple JFrame with a FlowLayout.

Am I using it wrong? How am I meant to trigger the mouse events?

JPanelMouseMotion class:

import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JPanel;

public class JPanelMouseMotion extends JPanel implements MouseMotionListener {

    private static final long serialVersionUID = 1L;

    public JPanelMouseMotion() {
        super();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        System.out.println(e.getX() + " / " + e.getY());
    }

}

Solution

  • The listener is never called because it is never registered. You should call addMouseMotionListener to register it.

    public class JPanelMouseMotion extends JPanel implements MouseMotionListener {
    
        private static final long serialVersionUID = 1L;
    
        public JPanelMouseMotion() {
            super();
            addMouseMotionListener(this); // register this JPanel as a Listener
        }
    
        @Override
        public void mouseDragged(MouseEvent e) {
        }
    
        @Override
        public void mouseMoved(MouseEvent e) {
            System.out.println(e.getX() + " / " + e.getY());
        }
    
    }