how to add mouse listener to JLabel which contain image

Java Curious ღ picture Java Curious ღ · Aug 21, 2013 · Viewed 13.5k times · Source

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.

Answer

misserandety picture misserandety · Aug 21, 2013

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