ValidateJFXTextField

0

Hi, I'm doing an application on Java FX with the JFONIX library I want to validate a JFXTesxtField so that I only accept numbers and another one to accept decimal numbers and that in the latter I can not enter more than 1 .

public void SoloNumerosEnteros(KeyEvent keyEvent) {
    try{
        char key = keyEvent.getCharacter().charAt(0);
        if(Character.isLetter(key))
            keyEvent.consume();

    }catch (Exception ex){  }
}

FXML file:

<JFXTextField fx:id="TxtTel" focusColor="#3f8bad" prefHeight="25.0" prefWidth="194.0" style="-fx-text-inner-color: WHITE;" unFocusColor="#178bad" onKeyTyped="#SoloNumerosEnteros" />

This same code in a Normal application works for me but in this (I assume) as .consume(); does not belong to the library javafx.scene.input.KeyEvent; does nothing% .consume(); . I hope you can help me solve these problems.

    
asked by Joaquin gonzalez 24.04.2018 в 00:22
source

1 answer

0

To add a validation in a text field of JavaFX I recommend that you do it using EventHandlers and from the code. If you add in the SceneBuilder the method that will be executed when an event occurs, this method will be called after the component has handled it, so the call to consume() will not have the expected effect for you.

That's what I would do

textField.setOnKeyTyped(event -> SoloNumerosEnteros(event));

EDITED:
For some reason that I do not know the previous code does not work in Java 9, maybe it is a bug (my version is 9.0.1). If you work with this version of Java use the following code instead of the previous one.

textField.addEventHandler(KeyEvent.KEY_TYPED, event -> SoloNumerosEnteros(event));

end of the edition

Additionally I recommend you use Character.isDigit() instead of Character.isLetter() , since for example an asterisk is not a letter and it would be allowed by your validation method.

public void SoloNumerosEnteros(KeyEvent keyEvent) {
    try{
        char key = keyEvent.getCharacter().charAt(0);

        if (!Character.isDigit(key))
            keyEvent.consume();

    } catch (Exception ex){ }
}
    
answered by 24.04.2018 / 03:15
source