2

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());
 }
}
asked Oct 2, 2015 at 13:25

1 Answer 1

4

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());
 }
}
answered Oct 2, 2015 at 13:28
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.