使用的时候,只要将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;
//SwingUtils 实用方法类
public class SwingUtils {
/**
* 对指定的button添加回车驱动事件的功能
* @param button
*/
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);
}