[Q#4546214][A#4546274] How to fire tab key event?
https://stackoverflow.com/q/4546214
How do we fire a tab key pressed event deliberately in Java? I also want to know how to fire a Shift + tab key pressed event programmatically in Java.
Answer
https://stackoverflow.com/a/4546274
The following example shows how to simulate mouse and key presses in Java using java.awt.Robot class. Edited my post to do the SHIFT + TAB Key Press.
APIzation
try {
Robot robot = new Robot();
// Simulate a mouse click
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
// Simulate a key press
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (AWTException e) {
e.printStackTrace();
}
package com.stackoverflow.api;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class Human4546274 {
public static void simulateMouseAndKeypress() {
try {
Robot robot = new Robot();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
package com.stackoverflow.api;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* How to fire tab key event?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/4546274">https://stackoverflow.com/a/4546274</a>
*/
public class APIzator4546274 {
public static void fireEvent() throws Exception {
try {
Robot robot = new Robot();
// Simulate a mouse click
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
// Simulate a key press
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (AWTException e) {
e.printStackTrace();
}
}
}