Control keyboard input into javafx TextField

后端 未结 6 1723
清酒与你
清酒与你 2020-12-31 17:44

I want to control the input into a Javafx TextField so that I can allow only Numeric input, and so that if the max characters are exceeded, then no change will be made to th

6条回答
  •  迷失自我
    2020-12-31 17:58

    Final solution. Disallows alphabetic and special characters and enforces character limit.

    import javafx.scene.control.TextField;
    
    public class AttributeTextField extends TextField{
    
        public AttributeTextField() {
            setMinWidth(25);
            setMaxWidth(25);
        }
    
        public void replaceText(int start, int end, String text) {
            String oldValue = getText();
            if (!text.matches("[A-Za-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
                super.replaceText(start, end, text);
            }
            if (getText().length() > 2 ) {
                setText(oldValue);
            }
        }
    
        public void replaceSelection(String text) {
            String oldValue = getText();
            if (!text.matches("[A-Za-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
                super.replaceSelection(text);
            }
            if (getText().length() > 2 ) {
                setText(oldValue);
            }
        }
    }
    

提交回复
热议问题