Control keyboard input into javafx TextField

后端 未结 6 1745
清酒与你
清酒与你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 17:58

    the best way is :

        @FXML
    private TextField txt_Numeric;
    @FXML
    private TextField txt_Letters;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        /* add Event Filter to your TextFields **************************************************/
        txt_Numeric.addEventFilter(KeyEvent.KEY_TYPED , numeric_Validation(10));
        txt_Letters.addEventFilter(KeyEvent.KEY_TYPED , letter_Validation(10));
    }
    
    /* Numeric Validation Limit the  characters to maxLengh AND to ONLY DigitS *************************************/
    public EventHandler numeric_Validation(final Integer max_Lengh) {
        return new EventHandler() {
            @Override
            public void handle(KeyEvent e) {
                TextField txt_TextField = (TextField) e.getSource();                
                if (txt_TextField.getText().length() >= max_Lengh) {                    
                    e.consume();
                }
                if(e.getCharacter().matches("[0-9.]")){ 
                    if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
                        e.consume();
                    }else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
                        e.consume(); 
                    }
                }else{
                    e.consume();
                }
            }
        };
    }    
    /*****************************************************************************************/
    
     /* Letters Validation Limit the  characters to maxLengh AND to ONLY Letters *************************************/
    public EventHandler letter_Validation(final Integer max_Lengh) {
        return new EventHandler() {
            @Override
            public void handle(KeyEvent e) {
                TextField txt_TextField = (TextField) e.getSource();                
                if (txt_TextField.getText().length() >= max_Lengh) {                    
                    e.consume();
                }
                if(e.getCharacter().matches("[A-Za-z]")){ 
                }else{
                    e.consume();
                }
            }
        };
    }    
    /*****************************************************************************************/
    

    Best of luck.

提交回复
热议问题