EventHandler JFXTextField

1

I have one more question, I have it separated in my project by folders in this way:

I have a folder (Main) for the main class with the method start(Stage stage) and the method main(String [] args) Another folder (Model) for business logic Another one for the Views that the application will have and finally another (ViewModel) for the Controller of each View.

SampleController code:

public class SampleController {

@FXML
private JFXTextField TxtWatts;

@FXML
public void initialize() {

    TxtWatts.setOnKeyTyped(event -> SoloNumerosEnteros(event));
}

public void SoloNumerosEnteros(KeyEvent keyEvent) {
    try{
        char key = keyEvent.getCharacter().charAt(0);
        if(!Character.isDigit(key))
            keyEvent.consume();
    }catch (Exception ex){
        System.out.println(ex.getMessage());
    }
}

}

    
asked by Joaquin gonzalez 24.04.2018 в 07:21
source

1 answer

0

You have everything to apply the EventHandler to your text field. You only need to add to the controller a method initialize() annotated with @FXML and within this the code corresponding to the handling of the event.

@FXML
private void initialize() {
     TxtWatts.setOnKeyTyped(event -> SoloNumerosEnteros(event));
}

It is important to clarify that the code that we have written within the initialize() method should not be added in the constructor of the class, since a NullPointerException would be thrown. This is because when the constructor is executed, all these attributes are null. On the contrary, the initialize() method is executed after the annotated attributes have been injected with @FXML (eg @FXML private JFXTextField TxtWatts).

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.

@FXML
private void initialize() {
     TxtWatts.addEventHandler(KeyEvent.KEY_TYPED, event -> SoloNumerosEnteros(event));
}
    
answered by 24.04.2018 / 07:55
source