如何从处理程序内调用外部方法
所以我在公共类中有一个 MouseListener 类,其中包含一些方法。 我已将 mouseListener 附加到公共类中的一个组件。
问题是我无法找到一种简单的方法来调用公共类中的方法,每当我说 this.showRemove();
时,作用域是来自处理程序类而不是公开课。这是一些示例代码
public class Game {
public Game() {
JPanel pnl = new JPanel();
pnl.addMouseListener(new GameMouseListener());
}
public void showRemove(){
//Code Here
}
class GameMouseListener implements MouseListener {
public void mouseClicked(MouseEvent e) {
this.showRemove(); //Can't Find Symbol Here
}
}
}
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.
The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove();
the scope is from within the handler class and not the public class. Here is some example code
public class Game {
public Game() {
JPanel pnl = new JPanel();
pnl.addMouseListener(new GameMouseListener());
}
public void showRemove(){
//Code Here
}
class GameMouseListener implements MouseListener {
public void mouseClicked(MouseEvent e) {
this.showRemove(); //Can't Find Symbol Here
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在内部类中使用
this
时,您指的是内部类的实例,而不是宿主类。由于您的内部类不是静态内部类,因此您可以通过使用主机类的类名来访问对主机类的引用,如下所示:
除非您调用的方法也在内部类中,否则您可以避免显式命名,可以简单地使用方法名称:
When you use
this
in an inner class, you are referring to the instance of the inner class, not the host class.Since your inner class is not a static inner class, you can access the reference to the host class by using it's class name like so:
Unless the method you're calling is also in the inner class, you can avoid the explicit naming and can simply use the method name:
由于
showRemove
是Game
的非静态方法,因此您需要该类的一个实例来调用该方法。您可以创建一个如下所示的匿名内部类:
此侦听器将与正在运行的 Game 实例关联,因此可以访问其非静态方法。
Since
showRemove
is a non-static method ofGame
you need an instance of that class on which to call the method.You could instead create an anonymous inner class like this:
This listener will be associated with the running instance of
Game
and will therefore have access to its non-static methods.您需要对 Game 对象的引用才能调用该方法。当您说 this.showRemoved() 时,“this”引用的是 MouseListener 对象而不是 Game 对象。
一种可能是让 Game 类扩展 MouseListener,并将 mouseClicked() 方法放在 Game 类中。
You need a reference to a Game object to be able to call the method. When you say this.showRemoved() "this" is referencing the MouseListener object instead of the Game object.
One possibility is to have the Game class extend MouseListener, and put the mouseClicked() method inside the Game class.