You can directly make the TextField
behave as though the backspace key has been pressed by calling target.deletePreviousChar()
, which is probably a far better approach.
To mimic the actual pressing of the Backspace key, you need the following changes:
- The text field reacts to
KEY_PRESSED
events, not KEY_TYPED
events. It's probably best to generate the whole sequence of events that happen when you type a key: KEY_PRESSED
, KEY_TYPED
, and KEY_RELEASED
.
- The text field must have focus. You can prevent the button from getting the focus with
source.setFocusTraversable(false)
.
- The
KeyCode
for KEY_TYPED
events should be UNDEFINED
(see docs).
Here's a SSCCE:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TriggerBackspaceOnTextField extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
Button backspace = new Button("Backspace");
backspace.setFocusTraversable(false);
backspace.setOnAction(e -> {
KeyEvent press = new KeyEvent(backspace, textField, KeyEvent.KEY_PRESSED, "", "", KeyCode.BACK_SPACE, false, false, false, false);
textField.fireEvent(press);
KeyEvent typed = new KeyEvent(backspace, textField, KeyEvent.KEY_TYPED, "", "", KeyCode.UNDEFINED, false, false, false, false);
textField.fireEvent(typed);
KeyEvent release = new KeyEvent(backspace, textField, KeyEvent.KEY_RELEASED, "", "", KeyCode.BACK_SPACE, false, false, false, false);
textField.fireEvent(release);
});
VBox root = new VBox(10, textField, backspace);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 350, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}