JavaFX TextField text validation

ぃ、小莉子 提交于 2020-07-03 20:19:17

问题


I have a listener applied to my field:

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

Event handler:

private EventHandler<KeyEvent> fieldChangeListener(final Integer max_Lengh) {
        return new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                TextField field = (TextField) event.getSource();
                String text = field.getText();
                // I need here something like:
                if(KeyEvent.VK_ENTER){
                // do special part for ENTER KEY
                }
            }
         }
}

Problem is KeyEvent event is from javafx.scene.input.KeyEvent and KeyEvent.VK_ENTER from com.sun.glass.events.KeyEvent. I don't know how can I determine if ENTER key triggered KEY_TYPED event.


回答1:


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));


来源:https://stackoverflow.com/questions/49918079/javafx-textfield-text-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!