我一直在寻找能够在两次按键之间有一个小延迟的方法。我一直在编写这个程序,它使用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);
}
}发布于 2012-07-19 07:04:26
以下是您可能遇到的一些问题(我还在下面添加了一个“完整”示例来完成此操作):
robot.keyRelease(c);
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);
}
}https://stackoverflow.com/questions/11551568
复制相似问题