1. 程式人生 > >java回車觸發按鈕的程式碼

java回車觸發按鈕的程式碼

可以實現回車觸發按鈕,或者是在文字輸入框的時候,回車觸發一個事件。

使用的時候,只要將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 {

    /**
     * 對指定的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);
    }

    /**
     * 在文字輸入框中回車觸發事件
     * @param textField
     * @param actionListener
     */
    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);
    }

}