我一直在寻找能够在按键之间产生短暂延迟的方法。我一直在制作这个程序,使用 JIntellitype 库读取全局热键,然后触发您分配的任何按键序列,例如按 numpad1 将执行 A B C 序列。我的问题是,如果我使用 Thread.sleep 它只需延迟 X 时间,然后按下所有指定的按键,在任何按键之间没有任何延迟。有人对如何解决这个问题有建议吗?
这就是我用来通过 Robot 类发送按键的内容
public void onHotKey(int identifier) {
try {
Robot bot = new Robot();
if (output.elementAt(identifier - 1).length() == 1) {
ch = output.elementAt(identifier - 1).charAt(0);
bot.keyPress(ch);
} else {
int cmdSize = output.elementAt(identifier - 1).length();
for (int c = 0; c < cmdSize; c++) {
bot.keyPress((int) output.elementAt(identifier - 1).charAt(c));
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} catch (AWTException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
这些是您可能遇到的一些问题(我还在下面添加了一个“完整”示例来执行此操作):
您只按下了按键,您还需要释放按键:
robot.keyPress(c); robot.keyRelease(c);
您可以在 EDT 中运行机器人。 使用另一个线程来处理按键...
使用“内置”auto delay
Robot
类已提供的功能:Robot robot = new Robot(); robot.setAutoDelay(50); // ms ...
示例:
这是一个如何实现此功能的示例,每次按 0
时,它都会打印 "hello"
,并使用自动延迟来延迟每个键入的字符:
public static void main(String[] args) throws Exception {
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(20);
JTextArea area = new JTextArea(10, 40) {{
addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_0) {
queue.offer(KeyEvent.VK_H);
queue.offer(KeyEvent.VK_E);
queue.offer(KeyEvent.VK_L);
queue.offer(KeyEvent.VK_L);
queue.offer(KeyEvent.VK_O);
}
}
});
}};
JFrame frame = new JFrame("Test");
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Robot robot = new Robot();
robot.setAutoDelay(50);
while (true) {
final int c = queue.take();
robot.keyPress(c);
robot.keyRelease(c);
}
}
关于java - 延迟按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11551568/