simulate Enter Key Pressed - Java Swing

Java examples for Swing:Key Event

Description

simulate Enter Key Pressed

Demo Code


//package com.java2s;
import java.awt.AWTEvent;
import java.awt.Component;

import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;

import javax.swing.SwingUtilities;

public class Main {
    public static void simulateEnterKeyPressed(final Component component,
            final int delayInMilliseconds) {
        final Runnable pressEnter = new Runnable() {
            @Override//from w  ww. ja  v a2s  . co m
            public void run() {
                KeyEvent keyEvent = new KeyEvent(component,
                        KeyEvent.KEY_PRESSED, System.currentTimeMillis(),
                        0, KeyEvent.VK_ENTER, (char) KeyEvent.VK_ENTER, 1);
                java.lang.reflect.Field f;
                try {
                    f = AWTEvent.class
                            .getDeclaredField("focusManagerIsDispatching");
                    f.setAccessible(true);
                    f.set(keyEvent, Boolean.TRUE);
                    component.dispatchEvent(keyEvent);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        };

        invokeDelayed(delayInMilliseconds, pressEnter);
    }

    public static void invokeDelayed(final int delayInMilliseconds,
            final Runnable action) {
        if (delayInMilliseconds == 0)
            SwingUtilities.invokeLater(action);
        else
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(delayInMilliseconds);
                        SwingUtilities.invokeAndWait(action);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }
}

Related Tutorials