Dennis De Roover Dennis De Roover - 3 months ago 51
Java Question

JavaFX - Getter for focused TextField out of an array of TextFields

I am looking for a way to forsee a getter in my program. I have a bunch of TextFields created dynamically:

fields = new TextField[105];
for (int i = 0; i < fields.length; i++) {
fields[i] = new TextField();
}


In my program it looks like this:

GameView for the TextFields

The objective of this program is to use the words in the List at the bottom of the picture and guess the words you have to fill in into the TextFields a.k.a. LetterPyramid. Therefore, I want to compare the text of the TextField that is focused with the correct answer that is read in into my program from a textfile. The problem I'm facing, is the fact that I have no clue on how to forsee a getter that returns the TextField out of the array that is currently focused. Is there anybody that can help me with that?

Thanks in advance!

Here are a few more blocks of code to help you understand my problem:

Here is the getter where I want to return the focused TextField

public TextField getField() {
return theFocusedTextField;
}


The handler that will receive the focused field and call the method checkInput() in my "model"-class.

view.getField().textProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.length() == 1) {
Log.debug("Old value: " + oldValue + "\nNew value: " + newValue);
boolean isCorrect = model.checkInput(newValue);
if (isCorrect) {
view.getField().setStyle("-fx-background-color: darkgreen; -fx-text-fill: white");
} else {
view.getField().setStyle("-fx-background-color: darkred; -fx-text-fill: white");
}
} else if (newValue.equals("")) {
view.getField().setStyle("-fx-background-color: darkred; -fx-text-fill: white");
}
});


At the moment, it receives a predefined field set by myself. The code for checking the answer works. Thanks for anyone that helps and if I find a way myself, I will definitely post it here.

Answer

Assuming you have defined:

private TextField theFocusedTextField ;

then all you need is:

fields = new TextField[105];
for (int i = 0; i < fields.length; i++) {
    TextField textField = new TextField();
    fields[i] = textField ;
    textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
        if (isNowFocused) {
            theFocusedTextField = textField ;
        } else {
            theFocusedTextField = null ;
        }
    });
}