How to force a double input in a TextField in JavaFX?

前端 未结 3 869
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 19:24

How to make sure an user inputs only double values in a given TextField?

I found a solution for integers bu I can\'t manage to use it for doubles.

3条回答
  •  臣服心动
    2021-01-06 20:05

    You can use the java regex on doubles and replace non-number characters with numbers. In you have to specify the number of digits allowed in the integer part, for example 1,10.

    textField.textProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, String oldValue, String newValue) {
            if (!newValue.matches("[0-9]{}(\\.[0-9]*)?")) {
                textField.setText(newValue.replaceAll("[^\\d.]", ""));
                StringBuilder aus = new StringBuilder(newValue);
                boolean firstPointFound = false;
                for (int i = 0; i < aus.length(); i++){
                    if(aus.charAt(i) == '.') {
                        if(!firstPointFound)
                            firstPointFound = true;
                        else
                            aus.deleteCharAt(i);
                    }
                }
                newValue = aus.toString();
            }
        }
    });
    

提交回复
热议问题