Issue
Im trying to prevent backspace from deleting characters in a javafx textarea. KeyEvent.consume
should do this but it doesn't prevent the key event from happening. It does set the property of the key event and KeyEvent.isConsumed()
gives back true after consuming the event. The backspace still gets executed. I tried other keys and there is the same effect.
This is my current fxcontroller class:
public class Terminal {
@FXML
private TextArea ta_console;
@FXML
private AnchorPane ap_main;
@FXML
protected void initialize(){
ta_console.setText(">");
ta_console.positionCaret(1);
}
public void keyStroke(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.BACK_SPACE || keyEvent.getCode() == KeyCode.DELETE) {
keyEvent.consume();
}
}
}
The keyStroke
method gets executed by the textarea on key pressed.
Am i missing something or is consume
bugged or somehow not functional the way the documentation says? Is there a way i can still get the desired outcome?
Solution
If you want to prevent the user deleting text, that should be done with a TextFormatter
instead of trying to guess which key events the control is handling internally, and in what order all those events are handled, etc. etc., for its default behavior.
It's not clear exactly what you want to achieve, but here is an example, which prevents any deletion (or replacement) of text:
public class Terminal {
@FXML
private TextArea taConsole;
@FXML
protected void initialize(){
taConsole.setText(">");
taConsole.positionCaret(1);
taConsole.setTextFormatter(new TextFormatter(change -> {
if (change.getRangeStart() == change.getRangeEnd()) { // nothing deleted
return change ;
}
// change represents a deletion of some text, veto it:
return null ;
});
}
}
See the Javadocs for TextFormatter.Change
for details.
Answered By - James_D
Answer Checked By - Candace Johnson (JavaFixing Volunteer)