5

I'm having some issues with getting my mouse events to work. I have a JPanel inside of a JLayeredPane which is in a JScrollPane. Admittedly, I am fairly new to working with Swing, but essentially, I want the JPanel to react to the mouse moving, but have been unable to get it to work.

public class CellHighlighter extends JPanel implements MouseMotionListener{

    public CellHighlighter(){

    }

    public void mouseMoved(MouseEvent evt){
        System.out.println(evt.getPoint().x + ", " + evt.getPoint().y);
    }

    public void mouseDragged(MouseEvent evt){System.out.println("message");}

}

Any help would be much appreciated, thanks in advance!

Shane Fitzgerald
  • 97
  • 2
  • 2
  • 5

2 Answers2

4

Are you registering your JPanel Object with the MouseListener? Something like:

    public CellHighlighter(){
       this.addMouseMotionListener(this);
    }

Or maybe you need to add the MouseListener to The ScrollPane or LayeredPane?

HectorLector
  • 1,851
  • 1
  • 23
  • 33
  • It should be emphasized that `addMouseMotionListener` is *required* even when the same instance has already be added via `addMouseListener`. – O. R. Mapper May 20 '14 at 12:32
2

Here's some demo code you can play with:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ReactPanel extends JPanel implements MouseMotionListener {

    public ReactPanel(){
        setPreferredSize(new Dimension(450, 450));
        setBackground(Color.GREEN);
        addMouseMotionListener(this);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        System.out.println("Mouse dragged (" + e.getX() + ',' + e.getY() + ')');
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        System.out.println("Mouse moved (" + e.getX() + ',' + e.getY() + ')');

    }

    public static void main(String[] args){
        //Create and set up the window.
        JFrame frame = new JFrame("MouseMotionEventDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ReactPanel();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
}
Allen Z.
  • 1,560
  • 1
  • 11
  • 19