0
votes

Is it possible to limit the input length in a JavaFX HTMLEditor? I tried to add an event handler to the editor and consume the event when the content reaches a predefined limit but it doesn't seem to work.

editor.addEventHandler(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent arg0) {
        if (editor.getHtmlText().length() >= MY_LIMIT) {
            arg0.consume();
        }
    }
});

Did anybody manage to achieve this? Is it even possible?

Thanks in advance.

1

1 Answers

0
votes

I'm sure there is a more elegant way to solve this problem, but the following code should work:

You need the two private class attributes

private static final int MAX_LENGTH = 250;
private String content;

and the following event handler

editor.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if(editor.getHtmlText().length() <= MAX_LENGTH) {
            content = editor.getHtmlText();
        }
    }
});

editor.setOnKeyReleased(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        if(editor.getHtmlText().length() > MAX_LENGTH) {
            editor.setHtmlText(content);
        }
    }
});