简体   繁体   English

如何从处理程序中引用对象

[英]How to refer to an object from within a handler

So I have a mouse listener that is attached to multiple objects as so: 因此,我有一个鼠标侦听器,它可以附加到多个对象:

for (int i = 0; i < Grids.size(); i++) {
     Grids.get(i).addMouseListener(new GameMouseListener()); 
   }

Now the problem I have is I need to know which of the Objects activated the handler 现在的问题是我需要知道哪个对象激活了处理程序

obviously this wont work since the var "i" is not defined inside the class and was only used in the previous for loop. 显然,这是行不通的,因为var“ i”未在类内部定义,仅在先前的for循环中使用。 how to I know using the Handler Which Specific Object has been clicked on. 我如何知道使用处理程序单击了哪个特定对象。

 public class GameMouseListener implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent e) {
        if (Grid.get(i).isSelected()) {

            Grid.get(i).unselected();
        } else {

            Grid.get(i).selected();
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

You can use e.getSource() to get the source of the event. 您可以使用e.getSource()获取事件的来源。

Also, consider using ActionListener when possible (if the user might select with the keyboard). 另外,请考虑尽可能使用ActionListener (如果用户可以使用键盘进行选择)。

And one more thing - it the listener is generic, you might create only one instance of it instead of new instance for each component: 还有一件事-如果侦听器是通用的,则可以只为其创建一个实例,而不是为每个组件创建新实例:

GameMouseListener listener = new GameMouseListener();
for (int i = 0; i < Grids.size(); i++) {
     Grids.get(i).addMouseListener(listener); 
}

you can pass the object on in the constructor as you are making a new one for each object anyway, (or use e.getSource() when you only create one listener) 您仍然可以在构造函数中传递该对象,因为无论如何您正在为每个对象创建一个新对象(或在仅创建一个侦听器时使用e.getSource()

for (int i = 0; i < Grids.size(); i++) {
   Grids.get(i).addMouseListener(new GameMouseListener( Grids.get(i))); 
}

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

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