0

My code:

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Scanner;

public class main
{
    public static void main(String[] args) throws Exception
    {       
        Thread.sleep(3000);

        int x = 66;
        int y = (int) 'b';

        Robot r = new Robot();          
        r.keyPress  (y);
        r.keyRelease(y);
        r.keyPress(x);
        r.keyRelease(x)         
    }
}

What has me really confused is, if the variable is a number, like x = 66, then r.keyPress(x) will output b - which is correct.

But if I have a variable with the character b and do:

char b = 'b';
int y = (int) b
r.keyPress(y)

It will output 2.

System.out.print(y) will output 66. I'm very confused.


I've read the posts, now my question is.. how would I go about: 1. Accept string from user 2. Type out the string with r.keyPress ?

user1021085
  • 729
  • 3
  • 10
  • 28

3 Answers3

3

Your 'b' is basically cast to an integer, giving it the value 98. That is the keycode for 2. Refer to the documentation for KeyEvent.

Irfy
  • 9,323
  • 1
  • 45
  • 67
  • How would I go about taking a string from the user then typing it with r.keyPress? – user1021085 Feb 20 '12 at 00:23
  • Off the top of my head -- I'm not sure. But I would look at [this method](http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#setKeyChar%28char%29) as a start. – Irfy Feb 20 '12 at 00:30
  • See also [this SO question](http://stackoverflow.com/questions/1248510/convert-string-to-keyevents), though I do not like the solutions there... – Irfy Feb 20 '12 at 00:31
  • Also, make sure you understand keycodes first. Keycodes are about physical keys on the keyboard, and combinations of presses thereof. So it is not necessarily trivial to map one to the other. Look at the [values behind the keycodes here](http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.awt.event.KeyEvent.VK_AT) – Irfy Feb 20 '12 at 00:40
2

I believe that for your keycodes that you're pressing to keyPress and keyRelease that you want to use constants from the KeyEvent class located here: http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html

VK_B seems to be equal to 66.

KeyEvent.VK_B should be the proper way to address the key for b, I think.

Daniel Lockard
  • 615
  • 3
  • 11
1

Robot's keyPress accepts a Key Code, not an ASCII value.

rtheunissen
  • 7,347
  • 5
  • 34
  • 65