JavaFX 2.2 TextField maxlength

后端 未结 9 1445
不知归路
不知归路 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:06
    private void registerListener1(TextField tf1, TextField tf2,TextField tf3,TextField tf4) {
        tf1.textProperty().addListener((obs, oldText, newText) -> {
    
            if(newText.length() == 12) {
    
                tf1.setText(newText.substring(0, 3));
                tf2.setText(newText.substring(tf1.getText().length(), 6));              
                tf3.setText(newText.substring(tf1.getText().length()+tf2.getText().length(), 9));
                tf4.setText(newText.substring(tf1.getText().length()+tf2.getText().length()+tf3.getText().length()));
                tf4.requestFocus();
            }
        });
    
    }
    
    private void registerListener(TextField tf1, TextField tf2) {
        tf1.textProperty().addListener((obs, oldText, newText) -> {
            if(oldText.length() < 3 && newText.length() >= 3) {
                tf2.requestFocus();
            }
        });
    
    }
    
    0 讨论(0)
  • The code below will re-position the cursor so the user doesn't accidentally overwrite their input.

    public static void setTextLimit(TextField textField, int length) {
        textField.setOnKeyTyped(event -> {
            String string = textField.getText();
    
            if (string.length() > length) {
                textField.setText(string.substring(0, length));
                textField.positionCaret(string.length());
            }
        });
    }
    
    0 讨论(0)
  • 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));
            }
    
        }
    };
    
    0 讨论(0)
提交回复
热议问题