javaswingjframemousemotionlistener

Can't provide coordinates of mouse to the `paintComponent()` method located in other class


I am creating a simple program which draws(displays) my image wherever the mouse is located. So the image moves with the mouse arrow.

For this I've created a JFrame and I've added MouseMotionListener and a Imageinto it by the class named Frame. Image is added using imageComponent class.

In MouseMotionListener I'm getting the mouse coordinate but can't understand how to provide these x and y coordinates to the paintComponent method, and how to repaint it every time when mouse is moved.Here is my code:

main() method in Practice class:

public class Practice {
public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable(){
      public void run(){
          JFrame frame = new Frame();
          frame.setSize(500,500);
          frame.setVisible(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
  });

} 
}

Frame class which add listener and ImageComponent to the frame.

class Frame extends JFrame{
Frame(){
    add(new imageComponent());
    addMouseMotionListener(new MouseAdapter(){
        public void mouseMoved(MouseEvent me){
            int x = me.getX();
            int y = me.getY();
            repaint();
        }
    });

}
}

imageComponent class, which draws image from specified path:

class imageComponent extends JComponent{
Image img;
int x,y;
imageComponent(){
    img = new ImageIcon("C:\\Users\\Kaushal28\\Desktop\\image.png").getImage();    
}

 public void paint(Graphics g){
    g.drawImage(img, x, y, null);
}
}

In above class I've declared x and y: the mouse coordinates. Which I want to get from the listener but can't understand how to do this. Please someone help!

EDIT: if I add mouseMotionListener to imageComponent then it is giving this errors:


Solution

  • Let the imageComponent add the mouse listener:

    class imageComponent extends JComponent {
    
        Image img;
        int x, y;
        imageComponent() {
            addMouseMotionListener(new MouseAdapter() {
                public void mouseMoved(MouseEvent me) {
                    x = me.getX();
                    y = me.getY();
                    repaint();
                }
            });
            img = new ImageIcon(/* path to image */).getImage();
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, x, y, null);
        }
    }