3

I have added an image to a Jlabel and I want to add mouse listener to it. I don't know to add a mouse listener to the Jlabel that contains the image.

So anyone who knows how to implement this please tell me.

I want to add a mousedragged listener to the JLabel. When the user drags it, it should work.

MouseHandler mk = new MouseHandler();
JLabel label = new JLabel();
label.addMouseListener(mk);

I have implemented a listener in the class that extends mouse adapter.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Java Curious ღ
  • 3,622
  • 8
  • 39
  • 63

3 Answers3

4

You can try :

     JLabel nameLabel = new JLabel("Name:");
     nameLabel.addMouseMotionListener(new MouseMotionAdapter() {
        //override the method
        public void mouseDragged(MouseEvent arg0) {
                     // to do .........................
        }
    });

thats the way I understand your question.

But I guess this can help you too : Drag and move a picture inside a JLabel with mouseclick

Community
  • 1
  • 1
misserandety
  • 122
  • 1
  • 4
  • 13
2

You are adding your mouse adapter as a mouse listener (which handles click, enter, exit, pressed, released). You want to add it as a mouse motions listener if you want to handle drag and move events.

Dodd10x
  • 3,344
  • 1
  • 18
  • 27
0

You can do following:

ImageIcon icon = new ImageIcon("C:/image.jpg"); //Path to the image  
JLabel label = new JLabel(icon); //add image to the label

label.addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseMoved(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseDragged(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
    }); 

You can add the actions to the above methods as required.

Abhishek
  • 375
  • 1
  • 4
  • 12