Java Swing Key Action simulateEnterKey(Component c)

Here you can find the source of simulateEnterKey(Component c)

Description

Example came from http://tech.chitgoks.com/2010/08/31/simulate-enter-key-on -any-component-using-java/

License

Open Source License

Parameter

Parameter Description
c a parameter

Declaration

public static void simulateEnterKey(Component c) 

Method Source Code


//package com.java2s;

import java.awt.Component;

import java.awt.event.KeyEvent;

import javax.swing.SwingUtilities;

public class Main {
    /**/* w  ww .  j av  a2 s. co m*/
     * Example came from
     * http://tech.chitgoks.com/2010/08/31/simulate-enter-key-on
     * -any-component-using-java/
     * 
     * @param c
     */
    public static void simulateEnterKey(Component c) {
        try {
            KeyEvent ke = new KeyEvent(c, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), -1, KeyEvent.VK_ENTER,
                    (char) KeyEvent.VK_ENTER);
            c.requestFocusInWindow();
            dispatchEvent(ke, c);
        } catch (Exception ex) {
        }
    }

    private static void dispatchEvent(final KeyEvent ke, final Component comp) throws Exception {
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    comp.dispatchEvent(ke);
                }
            });
        } else {
            comp.dispatchEvent(ke);
        }
    }
}

Related

  1. setKeyEvent(JComponent widget, int keyEvent, Runnable action)
  2. setMnemonic(Action action)
  3. setTabFocusTraversalKeys(final JComponent component)
  4. setupAction(Action action, ResourceBundle bundle, String actionId)
  5. setUseStandardFocusTraversalKeys(Component comp, boolean use)
  6. simulateEnterKeyPressed(final Component component, final int delayInMilliseconds)
  7. simulateKeyStrokes(Component comp, String text)
  8. stringify(KeyStroke keyStroke)
  9. stringToKey(String s)