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
}
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With