Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX TextArea remove default undo action for shortcut Ctrl+Z

Tags:

java

javafx

I am trying to make an editable Java FX TextArea, that doesn't have the ability to undo the last step with shortcut Ctrl+Z. By default, when you create an editable JavaFX TextArea, JavaFX provides the default undo/redo functionalities for the shortcuts Ctrl+Z/Ctrl+Y while that TextArea is focused (as well as copy, paste etc.). I would like to disable these default actions for the Shortcuts Ctrl+Z and Ctrl+Y to be able to create my own undo/redo logic instead of the default logic provided by JavaFX. Also: I don't want to disable the undo redo logic from JFX completely, since I am using it afterwards, (textarea.undo() and textarea.redo() must still be possible) I simply want to remove the KeyPress Events that are created by default, how can I do this?

Code: I've created a TextArea inside a BorderPane with FXML, and attached a Controller to the FXML, so the TextArea can be accessed by code, no css file is used.

like image 901
A. Markóczy Avatar asked Oct 29 '25 09:10

A. Markóczy


1 Answers

You have several options:

The common thing is that they are using the comsume() method of the Event class.

1) Using KeyCodeCombination:

TextArea ta = new TextArea();
final KeyCombination keyCombCtrZ = new KeyCodeCombination(KeyCode.Z, KeyCombination.SHORTCUT_DOWN;
final KeyCombination keyCombCtrY = new KeyCodeCombination(KeyCode.Y, KeyCombination.SHORTCUT_DOWN);
ta.setOnKeyPressed(new EventHandler<KeyEvent>() {

    @Override
    public void handle(KeyEvent event) {
        if (keyCombCtrZ.match(event) || keyCombCtrY.match(event) ) { 
            event.consume();
        }

    }
});

2) Using isShortcutDown() method of KeyEvent:

TextArea ta = new TextArea();
ta.setOnKeyPressed(new EventHandler<KeyEvent>() {

    @Override
    public void handle(KeyEvent event) {
        if ((event.getCode() == KeyCode.Z || event.getCode() == KeyCode.Y)
            && event.isShortcutDown()) {
            event.consume();
        }

    }
});
like image 113
DVarga Avatar answered Oct 31 '25 06:10

DVarga