JavaFX 2.2 TextField maxlength

George Siggouroglou picture George Siggouroglou · Mar 1, 2013 · Viewed 45.6k times · Source

I am working with a JavaFX 2.2 project and I have a problem using the TextField control. I want to limit the characters that users will enter to each TextField but I can't find a property or something like maxlength. The same problem was existing to swing and was solved with this way. How to solve it for JavaFX 2.2?

Answer

ceklock picture ceklock · Feb 24, 2014

This is a better way to do the job on a generic text field:

public static void addTextLimiter(final TextField tf, final int maxLength) {
    tf.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
            if (tf.getText().length() > maxLength) {
                String s = tf.getText().substring(0, maxLength);
                tf.setText(s);
            }
        }
    });
}

Works perfectly, except for that Undo bug.