How to associate pressing “enter” with clicking button?

这一生的挚爱 提交于 2020-01-01 08:47:26

问题


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.


回答1:


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.




回答2:


there is an example here

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

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




回答3:


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.



来源:https://stackoverflow.com/questions/4703152/how-to-associate-pressing-enter-with-clicking-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!