JavaFX KeyEvent and accented characters

2019-06-25 12:50发布

问题:

I'm using a WebView with a contenteditable body as a rich text editor in JavaFX. It's working fine, but I need to listen for key presses. It works for the enter key and ASCII characters, but accented characters (like the icelandic á and é) don't fire any event. I tried KeyEvent.KEY_PRESSED and KeyEvent.KEY_TYPED, and neither of them fire for accented characters.

InputMethodEvent does fire for accented characters, but if I setup a listener for that, it seems to automatically consume the event and it doesn't get to the editor.

Anybody know of a way to listen for event when accented characters are typed that doesn't consume them or of a way to unconsume the character in InputMethodEvent?

回答1:

You can add an KeyEvent EventHandler to any Node (in this case your WebView) with the Node.addEventHandler method, and if you handle the EventType KeyEvent.KEY_TYPED you can get the typed unicode characters with 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;
                            }
                        }

                    });

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

Good luck!