Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

automation - simulate backspace key with 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...