JavaFX 2.2 TextField maxlength

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

    You can do something similar to approach described here: http://fxexperience.com/2012/02/restricting-input-on-a-textfield/

    class LimitedTextField extends TextField {
    
        private final int limit;
    
        public LimitedTextField(int limit) {
            this.limit = limit;
        }
    
        @Override
        public void replaceText(int start, int end, String text) {
            super.replaceText(start, end, text);
            verify();
        }
    
        @Override
        public void replaceSelection(String text) {
            super.replaceSelection(text);
            verify();
        }
    
        private void verify() {
            if (getText().length() > limit) {
                setText(getText().substring(0, limit));
            }
    
        }
    };
    

提交回复
热议问题