Search code examples
javaimageswingjlabelmouselistener

how to add mouse listener to JLabel which contain image


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.


Solution

  • 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