I'm trying to use the Robot class in Java and type some text. Unfortunately I'm having problems finding the key codes of the square brackets, this symbol | and this symbol `. I can't find them in the KeyEvent constants. I want to use them, because the text i'm typing is in cyrillic and these symbols represent characters in the alphabet. Thanks in advance.
It's in the JavaDoc for KeyEvent
KeyEvent.VK_OPEN_BRACKET
and
KeyEvent.VK_CLOSE_BRACKET
Edit
From the KeyEvent JavaDoc
This low-level event is generated by a component object (such as a
text field) when a key is pressed, released, or typed.
So on a US 101-key keyboard, the ` and ~ will produce the same keycode, although ~ will have a SHIFT modifier. Also notice that KeyEvent.VK_BACK_SLASH traps the | (pipe) keystroke too.
Try adding the following sample KeyAdapter to your project to see this in action.
new KeyAdapter()
{
public void keyPressed(final KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_BACK_QUOTE)
{
e.toString();
}
if (e.getKeyCode() == KeyEvent.VK_BACK_SLASH)
{
e.toString();
}
if (e.getKeyCode() == KeyEvent.VK_OPEN_BRACKET)
{
e.toString();
}
}
}
The general solution is to call KeyEvent.getExtendedKeyCodeForChar(int c). If the unicode codepoint c has a VK_ constant that will be returned. Otherwise a "unique integer" is returned.
I think that '`' is KeyEvent.VK_BACK_QUOTE ...
Related
I started playing with java a little bit, after few years of coding in C#. What I am trying to achieve is to handle a key press event for jTextField.
In C# i would code:
e.Handled = true;
I did a little research and read that I can use consume() in java. So i wrote the following code:
if (evt.getKeyChar() == '.' || DataController.getInstance().isDot_pressed())
{
jTextFieldQuery.setText(DataController.getInstance().generateText(jTextFieldQuery.getText()));
if(evt.getKeyChar()!='.')
{
DataController.getInstance().setOdgovor(DataController.getInstance().getOdgovor()+evt.getKeyChar());
}
else
{
DataController.getInstance().setDot_pressed(!DataController.getInstance().isDot_pressed());
}
evt.consume();
}
}
This code should handle key pres for "." and every key press until another "." is pressed in the mean time it loads predefined text in text field.
This solution doesn't work, it consumes(handles) for example delete button but it doesn't handle normal letters.
Any suggestions? Thanks.
I have problem with press a special letter (Turkish etc.) via java robot class. I hava a method to press keys which works as alt+keycode. I cant convert some special letters to current keycode. So how can I solve it. Thanx
For Example:
KeyStroke ks = KeyStroke.getKeyStroke('ö', 0);
System.out.println(ks.getKeyCode());
Output : 246
// So alt+0246='ö'
//but if I convert 'ş' to keycode
//Output is 351 . So alt+351= '_' and alt+0351= '_'
//What is the Correct combination for 'ş'. same for 'Ş', 'ş','Ğ', 'ğ', 'İ', 'ı', 'Ə', 'ə'
KeyPress:
public void altNumpad(int... numpadCodes) {
if (numpadCodes.length == 0) {
return;
}
robot.keyPress(VK_ALT);
for (int NUMPAD_KEY : numpadCodes) {
robot.keyPress(NUMPAD_KEY);
robot.keyRelease(NUMPAD_KEY);
}
robot.keyRelease(VK_ALT);
}
The character numbers are defiunied in the Unicode standard. The are also used in HTML, therefore you can use this table.
Anyway if you see the character in the source code depends on the fact that the editor interprets the file correctly (UTF-8 is preferred).
Second the used editor must have a font installed that contains these characters. Hence if you type alt+0351 and get and '_' this may just be a replacement character indicating that the font misses this character.
And in the end you should tell the Java compiler that the source code is UTF-8 - just to make sure (javac -encoding utf8).
I am not sure why you did
KeyStroke ks = KeyStroke.getKeyStroke('ö', 0);
Because java docs say,
public static KeyStroke getKeyStroke(Character keyChar,
int modifiers)
//Use 0 to specify no modifiers.
you need to pass a modifier other than 0 to the overload.
You should try to pass a modification like,
java.awt.event.InputEvent.ALT_DOWN_MASK
So probably should try,
KeyStroke ks = KeyStroke.getKeyStroke('ö', java.awt.event.InputEvent.ALT_DOWN_MASK);
Java doc as reference: http://docs.oracle.com/javase/7/docs/api/javax/swing/KeyStroke.html#getKeyStroke(char)
If you cannot properly get a output from that then you should consider the fact the character is UTF-8
This might help you in that regard, Java, Using Scanner to input characters as UTF-8, can't print text
I know this is a late answer but here it is how I handle this problem for Turkish QWERTY keyboard
static void writeRobotWrite(Robot robot, String keys) throws InterruptedException {
....
try {
robot.keyPress(keyCode);
robot.delay(20);
robot.keyRelease(keyCode);
robot.delay(20);
}catch (IllegalArgumentException e)
{
pressUnicode(c, robot);
}
}
}
Basically when I got undefined keyCode for Robot I call pressUnicode function which is:
static void pressUnicode(char c, Robot robot)
{
String cantRecognize = ""+c;
StringSelection selection = new StringSelection(cantRecognize);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
Simply I'm just copying and pasting the character. This is working for all undefined characters. :)
I created a simple JavaFX application that receives input from the user in a TextField. I attached the KeyTyped event from SceneBuilder to the controller. My function looks like this:
#FXML private void keyTyped(KeyEvent event) {
System.out.println(event.getCode().equals(KeyCode.ENTER));
}
This function always prints out UNDEFINED when I type the enter key. Any ideas on how to fix this? Other letters I type seem to have the same problem as well.
KeyTyped is a special event. It doesn't have KeyCode but has character set instead.
See example for letter 'a':
KeyEvent [source = TextField[id=null, styleClass=text-input text-field],
target = TextField[id=null, styleClass=text-input text-field], eventType = KEY_TYPED, consumed = false,
character = a, text = , code = UNDEFINED]
and javadoc: http://docs.oracle.com/javafx/2/api/javafx/scene/input/KeyEvent.html#getCode()
The key code associated with the key in this key pressed or key
released event. For key typed events, code is always
KeyCode.UNDEFINED.
I have a piece of code that allows me to capture keystroke and print them with a System.out.println. My problem is that when I try to use it with ctrl (e.g. ctrl + m) it removes the KeyChar attribute of the m key. Does anyone know why this happen and how I can solve it?
public TestForm() {
initComponents();
KeyEventDispatcher keyEventDispatcher = new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(final KeyEvent e)
{
if (e.getID() == KeyEvent.KEY_PRESSED && e.isAltDown())
{
System.out.println("ALT + "+e.getKeyChar());
}
else if (e.getID() == KeyEvent.KEY_PRESSED && e.isShiftDown())
{
System.out.println("SHIFT + "+e.getKeyChar());
}
else if (e.getID() == KeyEvent.KEY_PRESSED && e.isControlDown())
{
System.out.println("CTRL + "+e.getKeyChar()/*+"\n"+e*/);
}
else
{
System.out.println(e);
}
return true;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatcher)
;
}
I'm quite new to java so it might be something simple im missing. Thanks in advance
There is an important difference between key code and key char. A key code represents a key on a keyboard. A key char represents a letter in some alphabet. There is a ctrl key on your keyboard but there is no letter in any alphabet (e.g. no unicode character) for ctrl. So when the ctrl key is pressed you get a KEY_PRESSED event with a key code but no key char.
Not all hope is lost though. It looks like you are trying to detect when CTRL and some character is pressed (e.g. if I type ctrl+A instead of just A). The problem is that you are looking at KEY_PRESSED events. In Java there is an important distinction between the KEY_PRESSED event and the KEY_TYPED event.
For exmaple, if I were to press Ctrl+A on my keyboard I would first press down the Ctrl key, then press down the A key, then release them more or less at the same time. In my mind I think of this as one action, but it's not. What happens in Java is you get:
KEY_PRESSED (keyCode = VK_CTRL, keyChar = CHAR_UNDEFINED) //I press down Ctrl key
KEY_PRESSED (keyCode = VK_A, keyChar = CHAR_UNDEFINED) //I press down the a key
KEY_TYPED (keyCode = VK_UNDEFINED, keyChar = 'A') //The 'typing' of the letter 'A'
//some key released events that are not relevant to this discussion
As you can see, a KEY_PRESSED event has a key code but no key char (this is fired when a key on the keyboard is pressed down). A KEY_TYPED event has a key char but not key code (this represents the completion of a key sequence resulting in a letter).
All of this is documented in detail on the javadocs for the KeyEvent page.
I want to generate key events for Special characters like £, €, µ, ½, Ö, Ä etc. I am able to generate keyevents for key which are on my keyboard like 'A,B,c, %, *, ^' etc with following code:
public static void generateKeyEvent(final int c) {
new Thread() {
public void run() {
try {
Robot robot = new Robot();
robot.keyPress(c);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
robot.keyRelease(c);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
In case of normal characters, it is working fine but in case of characters which i mentioned above the code is throwing following exception:
java.lang.IllegalArgumentException: Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at com.companyname.utils.Abc$1.run(Abc.java:286)
One thing which i noticed during my search for the solution to this problem, as these special characters are not mapped on my keyboard that is why it is throwing this exception.
any idea, how can i do this?
I got answer to this problem.. basically if you want to print symbol like those then you need to "alt" key for typing that.
for example: if you need to type 'é' in notepad you have to type alt+130.
So i did the same, i generated the key event for alt then for numpad 1 then numpad3 and finally numpad0.
How are you passing the keys?
Note that Robot.keyPress expects key code, not character. Take a look at the KeyEvent constants. There is a VK_EURO_SIGN, not sure about the others.
You should be able to get an arbitrary key code by implementing a KeyListener and checking KeyEvent.getKeyCode() when the particular key (combination of keys) is pressed.