简体   繁体   English

使用MouseListener在JLabel中设置和获取对象

[英]Setting and getting an object in a JLabel with a MouseListener

I have a JLabel with a MouseListener 我有一个带有MouseListenerJLabel

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? 有没有办法将对象与JLabel关联,以便我可以从mouseClicked方法中访问它?

Edit: 编辑:

To give a more illustrative example, what i am trying to do here is setting JLabels as graphical representation of playing cards. 为了给出一个更具说明性的例子,我在这里要做的是将JLabels设置为扑克牌的图形表示。 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. 所以我想将该Card对象与JLabel相关联。

Solution: 解:

As 'Hovercraft Full Of Eels' suggest, me.getSource() is the way to go. 正如'Hovercraft Full Of Eels' me.getSource()me.getSource()是要走的路。 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: 并从侦听器获取Card对象:

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. 您可以通过在所有MouseListener和MouseAdapter方法中返回的MouseEvent上调用getSource()来轻松获取单击的对象。 If the MouseListener was added to several components, then clicked one will be returned this way. 如果将MouseListener添加到多个组件中,则单击一个将以这种方式返回。

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. 注意:我通常更喜欢在mouseClicked()使用mousePressed()方法,因为它不那么“怯懦”并且即使鼠标在按下之后和释放之前移动也会记录按下。

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

Sure, one easy way would be to create a Constructor in ClickController that took in a JLabel . 当然,一种简单的方法是在ClickController中创建一个ClickController JLabel的构造函数。 Then you could access that specific JLabel within the object. 然后,您可以访问对象中的特定JLabel 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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