如何从处理程序中引用对象
所以我有一个附加到多个对象的鼠标侦听器,如下所示:
for (int i = 0; i < Grids.size(); i++) {
Grids.get(i).addMouseListener(new GameMouseListener());
}
现在我遇到的问题是我需要知道哪个对象激活了处理程序
显然这不会工作,因为 var“i” 没有在类中定义并且是仅在前面的 for 循环中使用。 如何使用处理程序知道哪个特定对象已被单击。
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) {
}
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.
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) {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
e .getSource()
获取事件源。另外,请考虑使用
ActionListener
如果可能的话(如果用户可以使用键盘进行选择)。还有一件事 - 如果侦听器是通用的,您可能只创建它的一个实例,而不是为每个组件创建新实例:
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:
无论如何,您可以在构造函数中传递该对象,因为您为每个对象创建一个新对象(或者当您只创建一个侦听器时使用
e.getSource()
)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)