如何使用操作监听器
我是 Swing 新手,需要一些关于动作侦听器的帮助。我见过它们像这样使用:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do something
}
});
但是我想做一些更像这样的事情:
button.addActionListener(myFunc);
public void myFunc(ActionEvent e)
{
// Do something
}
这可能吗?
I'm new to Swing and need some help with action listeners. I have seen them used like this example:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do something
}
});
However I want to do something more like this:
button.addActionListener(myFunc);
public void myFunc(ActionEvent e)
{
// Do something
}
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有两种可能的方法 - 您可以直接从您给出的第一个示例中调用 myFunc 方法:
...或者您可以定义一个实现 actionlistener 的内部类,然后使用它:
在未来的说明中,当 Java 8 达到架子(2013 年,所以不要屏住呼吸),您将能够使用闭包更简洁地完成此操作。
Two possible approaches here - either you can just call your myFunc method directly from within the first example you give:
...Or you can define an inner class that implements actionlistener and then use that:
On a futuristic note, when Java 8 hits the shelves (2013, so don't hold your breath) you'll be able to do this more concisely using closures.
如果您想避免额外的课程,您可以使用反射蹦床课程。我为此编写了一个实用程序类:
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/action/ReflectiveXAction.html
有关反射操作的更多信息:第 6.2.3 章,第 14 页Steve 的 Java 系列书籍 Java 平台性能策略和战术的第 73 部分威尔逊和杰夫·凯塞尔曼。
教程:
http://softsmithy.sourceforge.net/lib/docs /tutorial/swing/action/index.html
Maven:
下载:
http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.1/
If you want to avoid additional classes you could use a reflective trampoline class. I've written a utility class for this:
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/action/ReflectiveXAction.html
More to read about reflective actions: Chapter 6.2.3, p. 73 of the Java Series Book Java Platform Performance Strategies and Tactics by Steve Wilson and Jeff Kesselman.
Tutorial:
http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/action/index.html
Maven:
Download:
http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.1/
很简单:
...我知道这有点样板...但是 java 不支持将函数作为参数传递。
Quite simply:
...I know it's a bit boilerplate ...but java doesn't support passing functions as parameters.
仅当该方法返回
ActionListener
时才有可能,否则则不会。当然,将 ActionEvent 的处理委托给单独的方法是完全有效的。It would only be possible if the method returned an
ActionListener
, otherwise no. Of course, it's completely valid to delegate the handling of theActionEvent
to a separate method.如果您想使用 Java 8 lambda 表达式
或者作为其他答案的替代方案,对于较低版本的 Java,您可以使用匿名类。
If you want to use
Java 8
lambda expressionOr as an alternative to other answers, for lower versions of Java you can use an anonymous class.