简体   繁体   English

如何关联按“输入”与点击按钮?

[英]How to associate pressing “enter” with clicking button?

In my swing program I have a JTextField and a JButton. 在我的swing程序中,我有一个JTextField和一个JButton。 I would like for, once the user presses the "enter" key, the actionListener of the JButton runs. 我想,一旦用户按下“回车”键,JButton的actionListener就会运行。 How would I do this? 我该怎么做? Thanks in advance. 提前致谢。

JRootPane has a method setDefaultButton(JButton button) that will do what you want. JRootPane有一个方法setDefaultButton(JButton按钮),可以做你想要的。 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. 如果您的应用程序是JFrame,它会实现RootPaneContainer接口,您可以通过在JFrame上调用getRootPane()来获取根窗格,然后在返回的根窗格上调用setDefaultButton。 The same technique works for JApplet, JDialog or any other class that implements RootPaneContainer. 相同的技术适用于JApplet,JDialog或任何其他实现RootPaneContainer的类。

there is an example here 这里有一个例子

http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm

this is what you need: rootPane.setDefaultButton(button2); 这就是你需要的:rootPane.setDefaultButton(button2);

Get rid of ActionListeners. 摆脱ActionListeners。 That's the old style for doing listeners. 这是做听众的旧风格。 Graduate to the Action class. 毕业于Action课程。 The trick is to understand InputMaps and ActionMaps work. 诀窍是了解InputMaps和ActionMaps的工作原理。 This is a unique feature of Swing that is really quite nice: 这是Swing的一个独特功能,非常好用:

http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Here's how you do it: 这是你如何做到的:

JPanel panel = new JPanel();
panel.setLayout( new TableLayout( ... ) );
Action someAction = new AbstractAction( "GO" )  {
    public void actionPerformed() {
    }
};

InputMap input = panel.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );

input.put( KeyStroke.getKeyStroke( "enter", "submit" );
panel.getActionMap().put("submit", someAction );

panel.add( button = new JButton( someAction ) );
panel.add( textField = new JTextField( ) );

Using the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT allows the panel to receive keyboard events from any of it's child (ie ancestors). 使用WHEN_ANCESTOR_OF_FOCUSED_COMPONENT允许面板从其任何子节点(即祖先)接收键盘事件。 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. 因此,无论哪个组件具有焦点,只要它在面板内,按键将调用在ActionMap中的“submit”下注册的任何动作。

This allows you to reuse Actions in menus, buttons, or keystrokes by sharing them. 这允许您通过共享菜单,按钮或按键来重用Actions。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM