Naruto
Naruto

Reputation: 1810

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?

Upvotes: 0

Views: 4461

Answers (2)

Brian
Brian

Reputation: 17309

In your mouse listener:

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

Upvotes: 5

AlexR
AlexR

Reputation: 115328

What's wrong with label.removeMouseListener(listener)? It works just fine. If you want to create listener that removes itself call label.removeMouseListener(this)

Upvotes: 2

Related Questions