[英]simulate backspace key with java.awt.Robot
There seems to be an issue simulating the backspace key with java.awt.Robot
. 用
java.awt.Robot
模拟退格键似乎存在问题。
This thread seems to confirm this but it does not propose a solution. 该线程似乎证实了这一点,但未提出解决方案。
This works: 这有效:
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_A);
rob.keyRelease(KeyEvent.VK_A);
This doesn't: 这不是:
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_BACK_SPACE);
rob.keyRelease(KeyEvent.VK_BACK_SPACE);
Any ideas? 有任何想法吗?
It seems to work in this test. 似乎在此测试中有效。
Addendum: Regarding the cited article, "Aside from those keys that are defined by the Java language ( VK_ENTER
, VK_BACK_SPACE
, and VK_TAB
), do not rely on the values of the VK_ constants
. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future."— java.awt.event.KeyEvent
附录:关于被引用的文章,“除了Java语言定义的那些键(
VK_ENTER
, VK_BACK_SPACE
和VK_TAB
)之外,不依赖于VK_ constants
的值。Sun保留根据需要更改这些值的权利。将来可以容纳更多种类的键盘。” — java.awt.event.KeyEvent
public class RobotTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new RobotTest().create();
}
});
}
private void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setLayout(new FlowLayout());
f.add(new JTextField(8));
final JButton b = new JButton();
f.getRootPane().setDefaultButton(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.setText("@" + e.getWhen());
}
});
f.add(b);
f.setSize(256, 128);
f.setVisible(true);
doTest();
}
private void doTest() {
try {
Robot r = new Robot();
int[] keys = {
KeyEvent.VK_T, KeyEvent.VK_E,
KeyEvent.VK_S, KeyEvent.VK_T,
KeyEvent.VK_Z, KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_ENTER
};
for (int code : keys) {
r.keyPress(code);
r.keyRelease(code);
}
} catch (AWTException ex) {
ex.printStackTrace(System.err);
}
}
}
The Backspace functionality does not work as expected. 退格功能无法正常工作。 I added a Shift key with the Backspace and it works fine for me, here is the pseudo-code for it.
我在Backspace中添加了Shift键,它对我来说很好用,这是它的伪代码。
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_BACK_SPACE);
robot.keyRelease(KeyEvent.VK_BACK_SPACE);
robot.keyRelease(KeyEvent.VK_SHIFT);
This does not seem to work for the Delete key though. 不过,这似乎不适用于Delete键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.