Control keyboard input into javafx TextField

后端 未结 6 1752
清酒与你
清酒与你 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:51

    Try this solution add this function in your controller , you must add it on the keyPressed Action of your text field.

    @FXML
    void verifnum(KeyEvent event) {
    
        txt.textProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, String oldValue,
                    String newValue) {
                if (!newValue.matches("\\d*")) {
                    txt.setText(newValue.replaceAll("[^\\d]", ""));
                }
            }
        });
    }
    

提交回复
热议问题