Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and getting an object in a JLabel with a MouseListener

I have a JLabel with a MouseListener

label.addMouseListener( new ClickController() );

where the actions to perform are in

class ClickController{
...
public void mouseClicked(MouseEvent me) {
        // retrieve Label object
}

Is there any way to associate an object with the JLabel so i can access it from within the mouseClicked method?

Edit:

To give a more illustrative example, what i am trying to do here is setting JLabels as graphical representation of playing cards. The Label is intended to be the representation of an object Card which has all the actual data. So i want to associate that Card object with the JLabel.

Solution:

As 'Hovercraft Full Of Eels' suggest, me.getSource() is the way to go. In my particular case would be:

Card card = new Card();
label.putClientProperty("anythingiwant", card);
label.addMouseListener( new ClickController() );

and the get the Card object from the listener:

public void mouseClicked(MouseEvent me) {
   JLabel label = (JLabel) me.getSource();
   Card card = (Card) label.getClientProperty("anythingiwant");
   // do anything with card
}
like image 808
TMichel Avatar asked Jan 15 '23 03:01

TMichel


2 Answers

You can get the clicked object easily by calling getSource() on the MouseEvent returned in all MouseListener and MouseAdapter methods. If the MouseListener was added to several components, then clicked one will be returned this way.

i.e.,

public void mousePressed(MouseEvent mEvt) {
   // if you're sure it is a JLabel!
   JLabel labelClicked = (JLabel) mEvt.getSource();
}

note: I usually prefer using the mousePressed() method over mouseClicked() as it is less "skittish" and will register a press even if the mouse moves after pressing and before releasing.

like image 159
Hovercraft Full Of Eels Avatar answered Jan 17 '23 17:01

Hovercraft Full Of Eels


You could simply use a Map<JLabel, Card> (if you want to get a card from a label), or a Map<Card, JLabel> (if you want to get a label from a card).

like image 24
JB Nizet Avatar answered Jan 17 '23 17:01

JB Nizet