问题
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