2

I need some help. I have an ArrayList of Textfields.

 static List<TextField> lfLetters = new ArrayList<>();

And I want to check if the value has changed. And if it was I want to know which textfield it was. I know I can do this with a Listener but that only worked for a single one.

    TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
    System.out.println("textfield changed from " + oldValue + " to " + newValue);
});

I want it to work on an Array and determine which textfield has changed.

Thanks in advance!

DVarga
  • 21,311
  • 6
  • 55
  • 60
CaptainAaargh
  • 35
  • 1
  • 7

2 Answers2

2

You can use ObservableList with appropriate extractor and add listener directly to list. This way it will be automatically watching changes in the specified properties of its elements. It is more convenient, than adding listener to each text field, but in this case you can't get old value:

    ObservableList<TextField> oList = 
        FXCollections.observableArrayList(tf -> new Observable[]{tf.textProperty()});  

    oList.addListener((ListChangeListener.Change<? extends TextField> c) -> {
        while (c.next()) {
            if (c.wasUpdated()) {
                for (int i = c.getFrom(); i < c.getTo(); ++i) {
                    System.out.println("Updated index: " + i + ", new value: " + c.getList().get(i).getText());
                }
            }
        }
    });
whitesite
  • 827
  • 4
  • 12
1

I was thinking that I will mark this quesiton as a duplicate, as you have a totally similar question here.

But in the end, you want to have the reference to the TextField also in the listener, so I will add an answer.

This snippet adds 10 TextField objects to the ArrayList and adds a listener to each.

for (int i = 0; i < 10; i++) {
    TextField tf = new TextField();
    final int index = i;
    tf.textProperty().addListener((obs, oldVal, newVal) -> {
        System.out.println("Text of Textfield on index " + index + " changed from " + oldVal
                + " to " + newVal);
    });
    lfLetters.add(tf);
}

Or if your ArrayList is already initialized, you can iterate through it simply:

lfLetters.forEach(tf -> {
    tf.textProperty().addListener((obs, oldVal, newVal) -> {
        System.out.println("Text of Textfield on index " + lfLetters.indexOf(tf) + " changed from " + oldVal
                + " to " + newVal);
    });
});

Sample output

Text of Textfield on index 2 changed from InitialText - 2 to ModifiedText - 2
Text of Textfield on index 6 changed from InitialText - 6 to ModifiedText - 6
Community
  • 1
  • 1
DVarga
  • 21,311
  • 6
  • 55
  • 60
  • Note you can access the index more efficiently in the first example simply by doing `final int index = i;` immediately before adding the listener. – James_D Jul 16 '16 at 14:15