Search code examples
javauser-interfacetextareajavafx-2

JavaFX TextArea: how to set tabulation width


How do I set tab width of JavaFX TextArea ?

When I use tabulation (tab key) in TextArea, the width of the tabulation is wide. I want to control the width, i.e., use 4 spaces. In the documentation I could not find a method to do this.

I tried this code (where taInput is a TextArea), but it is not working as it should:

taInput.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent e) {
        if (e.getCode() == KeyCode.TAB) {
            // TAB SPACES
            StringBuilder sb = new StringBuilder(config.getTabSpacesCount());
            for (int i=0; i<config.getTabSpacesCount(); i++) {
                sb.append(' ');
            }
            taInput.insertText(taInput.getCaretPosition(), sb.toString());
            e.consume();
        }
    }
});

Solution

  • Finally I found a way to do this.

    It seems that the setOnKeyPressed() method is not good for this task because the event is handled after the keyPress action is executed.

    The addEventFilter() handles the events before their actions are executed, so you can manipulate the events.

    My new code:

    taInput.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent e) {
            if (e.getCode() == KeyCode.TAB) {
                String s = StringUtils.repeat(' ', config.getTabSpacesCount());
                taInput.insertText(taInput.getCaretPosition(), s);
                e.consume();
            }
        }
    });