JavaFX TextField text validation

前端 未结 1 1853
天涯浪人
天涯浪人 2021-01-29 00:55

I have a listener applied to my field:

nameTextField.addEventHandler(KeyEvent.KEY_TYPED, fieldChangeListener(50));

Event handler:<

相关标签:
1条回答
  • 2021-01-29 01:10

    If you want to do input validation when the text is changing, you could use a listener on the textProperty of the TextField:

    textField.textProperty().addListener((observable, oldValue, newValue) ->
        System.out.println("Input Validation"));
    

    To detect when Enter is pressed, you can use the onActionProperty

    textField.setOnAction(event -> System.out.println("Enter pressed: Word Check"));
    

    If you want to prevent the user to input characters that fails the validation logic, then rather than listening to the textProperty˙, you can use a TextFormatter (this TextField only accept integers):

    textField.setTextFormatter(new TextFormatter<>(change ->
             (change.getControlNewText().matches("([1-9][0-9]*)?")) ? change : null));
    
    0 讨论(0)
提交回复
热议问题