Setting up and getting an object in JLabel using MouseListener

I have MouseListener with MouseListener

 label.addMouseListener( new ClickController() ); 

where are the actions performed in

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

Is there a way to associate an object with JLabel so that I can access it from the mouseClicked method?

Edit:

To give a better example, what I'm trying to do here is set JLabels as a graphical representation of playing cards. The label is intended to represent an object map containing all the actual data. Therefore, I want to associate this map object with JLabel.

Decision:

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

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

and 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 } 
+4
source share
3 answers

You can easily get an object with a click by calling getSource() in MouseEvent, which was returned in all MouseListener and MouseAdapter methods. If MouseListener has been added to several components, then clicked one, which will be returned in 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 to use the mousePressed() method compared to mouseClicked() , because it is less "shy" and logs the press, even if the mouse moves after clicking and before releasing.

+6
source

You can simply use Map<JLabel, Card> (if you want to get a card from the tag) or Map<Card, JLabel> (if you want to get a shortcut from the card).

+2
source

Of course, one simple way would be to create a constructor in ClickController that would take JLabel . Then you can access this particular JLabel inside the object. For instance:

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

Source: https://habr.com/ru/post/1443747/


All Articles