将 ActionListener 与 JButton 结合使用
所以,我对 java 编程接口有点陌生。我有一个 JButton 菜单,其中每个 JButton 都有一个与之关联的操作(所以我使用 new JButton(action)),但是一旦选择了按钮,我想关闭菜单,所以我有一个 ActionListener 附加到每个 JButton就是这样做的。
出于美观的原因,我希望 ActionListener 位于 JButton 的操作之前,但我找不到一种不涉及添加新线程或创建新类的方法...有人有任何想法吗?另外,我使用的是 Java 1.4,所以没有什么花哨的新东西。
So, I am kind of new to programming interfaces with java. I have a menu of JButtons, where each JButton has an action associated with it (so I use new JButton(action)), however once a button is selected, I want to close the menu, so I have an ActionListener attached to each JButton that does that.
For prettiness reasons, I would like it if the ActionListener went before the JButton's action, but I cannot find a way to do that does not involve adding a new thread or creating a new class... Does anyone have any ideas? Also, I am using Java 1.4, so none of the fancy new stuff.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种可靠的方法是使用内部类 - 我知道您不想创建自己的类,但这使其变得非常简单。
Alternative, reliable approach, using an inner class - I know you didn't want to create your own class but this keeps it quite simple.
编辑:由于无法保证添加操作的执行顺序而被认为不正确 - 请参阅注释
可以使用函数分配操作:
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/AbstractButton.html#setAction%28javax.swing.Action%29
而不是传递它通过构造函数传入,然后分配它:
代码是伪/未经测试的,但这是我要尝试的第一件事。
EDIT: deemed incorrect due to there being no guarrantee on the order in which added actions are performed - see comments
Action can be assigned using a function:
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/AbstractButton.html#setAction%28javax.swing.Action%29
Rather than passing it in via the constructor, just assign it afterwards:
Code is pseudo/untested, but that's the first thing I would try.