I am working on a JavaFX project and I have a problem using the TextField control. I want to limit the characters that users will enter to each TextField to one. I found a solution if you use a single textfield with a Listener:
public static void addTextLimiter(final TextField tf, final int maxLength) {
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
if (tf.getText().length() > maxLength) {
String s = tf.getText().substring(0, maxLength);
tf.setText(s);
}
}
});
But the problem is that I have an Array of TextFields. Do you guys maybe know how I can rewrite this listener for a TextFieldArray?
Array list implementation:
static public TextField[] tfLetters = new TextField[37];
Initialisation of the array:
private void layoutNodes() {
int letternummer = 0;
for (int i = 1; i < 8; i++) {
for (int j = 0; j < i + 1; j++) {
this.tfLetters[letternummer] = new TextField("Letter " + i);
this.add(tfLetters[letternummer], j, i);
tfLetters[letternummer].setPadding(new Insets(5, 30, 5, 5));
tfLetters[letternummer].setAlignment(Pos.CENTER);
tfLetters[letternummer].setMinSize(10, 10);
letternummer++;
}
}
I used the given solution:
Arrays.asList(tfLetters).forEach(tfLetters -> GamePresenter.addTextLimiter(tfLetters,1));
GamePresenter is the presenter of the view where the Listener is written. In the view "GameView" I have implemented the Array of textfields. But now when I run the given solution I go the following NullPointerException:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at be.kdg.letterpyramide.view.GameView.GamePresenter.addTextLimiter(GamePresenter.java:36)
at be.kdg.letterpyramide.view.GameView.GameView.lambda$layoutNodes$0(GameView.java:52)
at java.util.Arrays$ArrayList.forEach(Arrays.java:3880)
GameView line: 36
tf.textProperty().addListener(new ChangeListener<String>() {
GameView line: 52
Arrays.asList(tfLetters).forEach(tfLetters -> GamePresenter.addTextLimiter(tfLetters,1));
Sidenote: I made it public static so I can use it in my GamePresenter. I'm very new to Java.
Thanks in advance!