Keycode event for BACKSPACE in JavaFx

谁都会走 提交于 2019-12-10 17:29:36

问题


I am doing a project in JavaFX, using Java 8 and Gluon scenebuilder. I want to detect when backspace is pressed inside a TextField. This is the code I am using:

public void keyPressed(KeyEvent kEvent) {
    if (kEvent.getCode() == KeyCode.BACK_SPACE) {
        System.out.println("Backspace pressed");
    }

This code is inside the controller file, called FXMLDocumentController, which controls the GUI xml file FXMLDocument. You can see from the image below the function is called whenever a key is typed inside TextField. This works with all the letters/numbers, but not with backspace.

Gluon scene builder settings

Theoretically it should work, but it doesn't.

How can I manage typing of the backspace button?

Edit:

Notice that putting this exact function on the root of the elements, on the "Window itself" (which is the AnchorPane) works. The problem is with reading the pressing of the backspace inside the TextField. You can see in the image below where I've put the function:

On the window backspace's detecting works


回答1:


You should use your keyPressed method in either on key pressed or on key released.

In the Docs, it states that:

No key typed events are generated for keys that don't generate Unicode characters (e.g., action keys, modifier keys, etc.).

Backspace is consider an Action Key.




回答2:


In the screenshot of your SceneBuilder I can see you are referencing the keyPressed(KeyEvent kEvent) controller method with On Key Typed not On Key Pressed.

For events of KeyEvent.KEY_TYPED the value of getCode() is always KeyCode.UNDEFINED.


Edit: I came back to this answer and reread your question. I want to clarify something but what I said above is still correct.

In your edit you mention the "exact" same setup works with the AnchorPane but when looking at your screenshot there are some differences. For your AnchorPane you have the controller method referenced for all three types: On Key Pressed, On Key Released, and On Key Typed.

This means that the method should be called up to 3 times for each key stroke (when the events reach the AnchorPane). Once when pressed, once for typed (if the key is capable of sending typed events - see the answer by Sedrick for clarification), and then once for released. Because of this, the method will work for the pressed and released events, but it won't work for the typed events.

In other words, the reason your code works for the AnchorPane but not the TextField is because you configured it correctly for the AnchorPane but not the TextField.



来源:https://stackoverflow.com/questions/49564002/keycode-event-for-backspace-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!