简体   繁体   中英

Keycode event for BACKSPACE in JavaFx

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

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 .

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 (eg, action keys, modifier keys, etc.).

Backspace is consider an Action Key .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM