JavaFX 2.2 TextField maxlength

后端 未结 9 1490
不知归路
不知归路 2020-12-03 11:47

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

9条回答
  •  难免孤独
    2020-12-03 12:01

    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() {
            @Override
            public void changed(final ObservableValue 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.

提交回复
热议问题