如何将按“Enter”键与“Enter”键关联起来?单击按钮?
在我的 swing 程序中,我有一个 JTextField 和一个 JButton。我希望,一旦用户按下“enter”键,JButton 的actionListener 就会运行。我该怎么做? 提前致谢。
In my swing program I have a JTextField and a JButton. I would like for, once the user presses the "enter" key, the actionListener of the JButton runs. How would I do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JRootPane 有一个方法 setDefaultButton(JButton button) 可以执行您想要的操作。如果您的应用程序是 JFrame,它实现 RootPaneContainer 接口,您可以通过在 JFrame 上调用 getRootPane() 来获取根窗格,然后在返回的根窗格上调用 setDefaultButton。相同的技术适用于 JApplet、JDialog 或任何其他实现 RootPaneContainer 的类。
JRootPane has a method setDefaultButton(JButton button) that will do what you want. If your app is a JFrame, it implements the RootPaneContainer interface, and you can get the root pane by calling getRootPane() on the JFrame, and then call setDefaultButton on the root pane that was returned. The same technique works for JApplet, JDialog or any other class that implements RootPaneContainer.
这里有一个例子
http://www.java2s.com/Code/ Java/Swing-JFC/SwingDefaultButton.htm
这就是您所需要的:rootPane.setDefaultButton(button2);
there is an example here
http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm
this is what you need: rootPane.setDefaultButton(button2);
摆脱 ActionListeners。这是做听众的旧风格。毕业至动作班。诀窍是理解InputMaps 和ActionMaps 的工作原理。这是 Swing 的一个独特功能,非常好:
http:// download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
操作方法如下:
使用 WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 允许面板从其任何子项(即祖先)接收键盘事件。因此,无论哪个组件具有焦点,只要它位于面板内,击键都会调用 ActionMap 中“提交”下注册的任何操作。
这允许您通过共享来重用菜单、按钮或击键中的操作。
Get rid of ActionListeners. That's the old style for doing listeners. Graduate to the Action class. The trick is to understand InputMaps and ActionMaps work. This is a unique feature of Swing that is really quite nice:
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Here's how you do it:
Using the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT allows the panel to receive keyboard events from any of it's child (i.e. ancestors). So no matter what component has focus as long as it's inside the panel that keystroke will invoke any action registered under "submit" in the ActionMap.
This allows you to reuse Actions in menus, buttons, or keystrokes by sharing them.