简体   繁体   中英

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
}

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.

ie,

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.

您可以简单地使用Map<JLabel, Card> (如果您想从标签上获取卡片),或者使用Map<Card, JLabel> (如果您想从卡片中获取标签)。

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM