使用的时候,只要将SwingUtils .enterPressesWhenFocused(JButton)这样就可以实现回车时候,触发按钮。
另外文本输入框回车触发事件则是:SwingUtils .enterPressesWhenFocused(JTextField textField,ActionListener actionListener) 。其中actionListener是需要触发的事件。
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class SwingUtils {
public static void enterPressesWhenFocused(JButton button) {
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
}
public static void enterPressesWhenFocused(JTextField textField,
ActionListener actionListener) {
textField.registerKeyboardAction(actionListener,
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
textField.registerKeyboardAction(actionListener,
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
}
}