开发者

How to refer to an object from within a handler

S开发者_高级运维o 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. 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.

Also, consider using ActionListener when possible (if the user might select with the keyboard).

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)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜