Java Swing Key Action simulateKeyStrokes(Component comp, String text)

Here you can find the source of simulateKeyStrokes(Component comp, String text)

Description

simulate Key Strokes

License

Open Source License

Declaration

public static void simulateKeyStrokes(Component comp, String text) throws Exception 

Method Source Code


//package com.java2s;

import java.awt.Component;

import java.awt.event.KeyEvent;

import javax.swing.SwingUtilities;

public class Main {
    public static void simulateKeyStrokes(Component comp, String text) throws Exception {
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            simulateKeyStroke(comp, c);/*from  ww  w  . j  a  v  a 2 s . com*/
        }
    }

    public static void simulateKeyStroke(Component c, char ch) {
        try {
            KeyEvent ke = new KeyEvent(c, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED,
                    (char) ch);
            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. setTabFocusTraversalKeys(final JComponent component)
  2. setupAction(Action action, ResourceBundle bundle, String actionId)
  3. setUseStandardFocusTraversalKeys(Component comp, boolean use)
  4. simulateEnterKey(Component c)
  5. simulateEnterKeyPressed(final Component component, final int delayInMilliseconds)
  6. stringify(KeyStroke keyStroke)
  7. stringToKey(String s)
  8. stringToKeys(String s)
  9. translate(KeyStroke keyStroke, Locale locale)