TMichel
TMichel

Reputation: 4442

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
}

Upvotes: 4

Views: 2921

Answers (3)

JB Nizet
JB Nizet

Reputation: 691755

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).

Upvotes: 2

Joe
Joe

Reputation: 366

Sure, one easy way would be to create a Constructor in ClickController that took in a JLabel. Then you could access that specific JLabel within the object. For example:

class ClickController{
    private JLabel label;
    public ClickController(JLabel label){
        this.label = label;
    }    ...
    public void mouseClicked(MouseEvent me) {
        label.getText()//Or whatever you want
    }
}

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 7

Related Questions