使用 java.awt.Robot 模拟退格键 [英] simulate backspace key with java.awt.Robot

查看:27
本文介绍了使用 java.awt.Robot 模拟退格键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 java.awt.Robot 模拟退格键似乎有问题.

There seems to be an issue simulating the backspace key with java.awt.Robot.

这个帖子 似乎证实了这一点,但没有提出解决方案.

This thread seems to confirm this but it does not propose a solution.

这有效:

Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_A);
rob.keyRelease(KeyEvent.VK_A);

这不会:

Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_BACK_SPACE);
rob.keyRelease(KeyEvent.VK_BACK_SPACE);

有什么想法吗?

推荐答案

在本次测试中似乎有效.

It seems to work in this test.

附录:关于引用的文章,除了那些由 Java 语言定义的键(VK_ENTERVK_BACK_SPACEVK_TAB),不要依赖 VK_ 常量 的值.Sun 保留根据需要更改这些值的权利,以适应未来更广泛的键盘."—java.awt.event.KeyEvent

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

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);
        }
    }
}

这篇关于使用 java.awt.Robot 模拟退格键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆