JavaFX KeyEvent and accented characters

I am using WebView with content content as a text editor in JavaFX. It works great, but I need to listen for keystrokes. It works to enter key and ASCII characters, but accented characters (like Icelandic and é) do not fire any events. I tried KeyEvent.KEY_PRESSED and KeyEvent.KEY_TYPED, and none of them shot for accented characters.

InputMethodEvent runs for accented characters, but if I set up a listener for this, it seems to automatically consume the event and not get into the editor.

Does anyone know a way to listen for an event when accented characters are typed that don't consume them, or a way not to use a character in InputMethodEvent?

+4
source share
1 answer

You can add a KeyEvent EventHandler to any Node (in this case your WebView) using the Node.addEventHandler method and if you handle EventType KeyEvent.KEY_TYPED, you can get unicode typed characters using the KeyEvent.getCharacter method. See this example:

WebView myWebView = new WebView(); myWebView.addEventHandler(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { System.out.println("Unicode character typed: "+event.getCharacter()); switch (event.getCharacter()) { case "á": System.out.println("Typed accented a"); break; case "é": System.out.println("Typed accented e"); break; case "í": System.out.println("Typed accented i"); break; case "ó": System.out.println("Typed accented o"); break; case "ú": System.out.println("Typed accented u"); break; default: System.out.println("Typed other key " + event.getCode()); break; } } }); 

Perhaps you should take a look at the Collator class if you want to compare different strings, ignoring locale, uppercase, lowercase, etc. This can be useful if you want to consider "á" and "a" equal.

Good luck

+1
source

All Articles