如何使用`Robot`类将键盘输入到控制台?

时间:2014-11-25 06:29:29

标签: java swing keyboard

我正在尝试使用swing实现虚拟键盘。我已经制作了自己的设计,现在如果我按下button A它应该在控制台上打印A。这该怎么做。?截至目前,我做了很多......

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    //System.out.println(" "+evt.getSource());
    if(evt.getSource()==jButton8)
    {
        try{
            Robot robot = new Robot(); 
            robot.keyPress(KeyEvent.VK_A); 
            }
            catch(Exception E){}
    }
}  

任何人都可以帮助我,我在NetBeans IDE中这样做。

1 个答案:

答案 0 :(得分:0)

虽然您的问题并不完全清楚,但以下代码可能会有所帮助:

public class VirtualKeyboardRobot {
    private Robot robot;

    public static void main(final String[] args) {
        try {
            new VirtualKeyboardRobot().test();
        } catch (final AWTException e) {
            e.printStackTrace();
        }
    }

    private void test() throws AWTException {
        final JFrame frame = new JFrame("Keyboard input to console using robot");
        frame.setAlwaysOnTop(true);
        frame.setFocusable(false);
        frame.setBounds(100, 100, 800, 200);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        robot = new Robot();
        robot.setAutoDelay(100);
        final ActionListener buttonListener = actionEvent -> {
            // See KeyEvent.VK_A: VK_A through VK_Z are the same as ASCII 'A' through 'Z' (0x41 - 0x5A).
            final Object source = actionEvent.getSource();
            if (source instanceof AbstractButton) {
                // Switch from the virtual keyboard to the previous window.
                typeKey(KeyEvent.VK_TAB, KeyEvent.ALT_MASK);
                // Type the key.
                typeKey((int) ((AbstractButton) source).getText().toUpperCase().charAt(0));
            }
        };
        final JPanel keyboardPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        for (char key = 'a'; key <= 'z'; key++) {
            final JButton button = new JButton(Character.toString(key));
            button.setFocusable(false);
            keyboardPanel.add(button);
            button.addActionListener(buttonListener);
        }
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(keyboardPanel, BorderLayout.NORTH);
        final JTextArea textArea = new JTextArea(6, 28);
        textArea.setFocusable(false);
        frame.getContentPane().add(textArea, BorderLayout.CENTER);
        frame.setVisible(true);
    }

    private void typeKey(final int keyCode, final int mask) {
        if ((mask & KeyEvent.ALT_MASK) != 0)
            robot.keyPress(KeyEvent.VK_ALT);

        typeKey(keyCode);

        if ((mask & KeyEvent.ALT_MASK) != 0)
            robot.keyRelease(KeyEvent.VK_ALT);
    }

    private void typeKey(final int keyCode) {
        robot.keyPress(keyCode);
        robot.keyRelease(keyCode);
    }
}