0

I want to make sure that the user can only write Numbers in the text field. But whenever I call textfield.setText(oldValue);, it won't update the text in the text field (it's not deleting the invalid characters).

    public class Controller{

    @FXML
    private TextField textfield;
    
    @FXML
    void initialize(){
        System.out.println("initialized setup window");
    
        textfield.textProperty().addListener(new ChangeListener<String>() {
    
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, 
                String newValue) {
                if (!newValue.matches("\\d*")) {
                    System.out.println("wrong character!");
                    System.out.println("new Value : "+newValue);
                    System.out.println("old Value : "+oldValue);
                    textfield.setText(oldValue);
                }
            }
        });
        
        
    }
    
Carl
  • 25
  • 6
  • 1
    wrong approach (the general rule is: don't change the state of the sender in a listener) - use a textFormatter instead – kleopatra Mar 30 '21 at 12:05
  • 1
    Search for `TextFormatter`. Maybe one (or more) of these will help. https://stackoverflow.com/questions/45977390/how-to-force-a-double-input-in-a-textfield-in-javafx , https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat , https://stackoverflow.com/questions/31039449/java-8-u40-textformatter-javafx-to-restrict-user-input-only-for-decimal-number – Abra Mar 30 '21 at 12:10
  • Aha, thank you very much! – Carl Mar 30 '21 at 12:25

0 Answers0