Search code examples
javaswingjlabelmouselistener

Removing MouseListener() from a JLabel


I added a MouseListener to a JLabel. Now if I want to disable this MouseListener associated with the JLabel, when the label is clicked once, how can I do it.

I know there is a big way to set a boolean or int variable when the label is clicked and then call a method and remove MouseListener there, but I want to learn a compact and easy way. Is there a way to do this?


Solution

  • In your mouse listener:

    public void mouseClicked(MouseEvent event) {
        // Do stuff...
        ((Component) event.getSource()).removeMouseListener(this);
    }