JavaFX 2.2 TextField maxlength

后端 未结 9 1478
不知归路
不知归路 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

    I'm using a simpler way to both limit the number of characters and force numeric input:

    public TextField data;
    public static final int maxLength = 5;
    
    data.textProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable,
                String oldValue, String newValue) {
            try {
                // force numeric value by resetting to old value if exception is thrown
                Integer.parseInt(newValue);
                // force correct length by resetting to old value if longer than maxLength
                if(newValue.length() > maxLength)
                    data.setText(oldValue);
            } catch (Exception e) {
                data.setText(oldValue);
            }
        }
    });
    

提交回复
热议问题