How to associate pressing “enter” with clicking bu

2019-04-05 03:18发布

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.

3条回答
太酷不给撩
2楼-- · 2019-04-05 03:44

there is an example here

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

this is what you need: rootPane.setDefaultButton(button2);

查看更多
神经病院院长
3楼-- · 2019-04-05 03:56

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:

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 (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.

查看更多
Luminary・发光体
4楼-- · 2019-04-05 03:58

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.

查看更多
登录 后发表回答