Search code examples
javaunicodecursor

Sending Unicode Text to Cursor Position in Java


Doing linguistics and phonetics, I often need to use certain special phonetic symbols. Although I'm using a special keyboard layout that enables me to write some of those characters by typing, they key combinations can often get both quite complex and highly repetitive, so I would like to create a litle app that would contain some buttons, perhaps, each of them capable of sending a specified (phonetic) symbol to whatever the current cursor position is, no matter what window on one's screen is in focus.

Is anything of this sort possible to do in Java?

I've seen a solution that copies the values into clipboard and then pastes them (Java paste to current cursor position), but that is not a very clean way to do it, is it? Is there a way better than just pasting the charactedr(s) via ctrl+V?

Many thanks for any help or advice in advance!

P.


Solution

  • You can use the AWT Robot to generate key press events. This will not provided the ability to insert arbitrary unicode characters but you can combine it with the technique you already described: transfer the unicode characters to the clipboard and generate a CTRL+V key event afterwards. You can try to save and restore the original clipboard content but this will work with types supported by Java only.

    The focus problem mentioned in the comments can be solved by setting the window to not receive the focus via Window.setFocusableWindowState with an argument of false.

    An alternative is to provide the unicode text via drag&drop. Most applications support dropping text in their input fields. The code for exporting the text is very similar as both, clipboard and d&d use the same interfaces in Java.