I have a slew of TextFields, where I need to place a ChangeListener on their respective focusedProperty. Instead of creating a ChangeListener for each individual TextField, I want to write a generic ChangeListener<Boolean> one time, then re-use that by assigning it to each TextFields focusedProperty. Then, within that ChangeListener, I would like to use the observable object passed into the ChangeListener to somehow gain reference back to the TextField class so that I can get to the actual text that the user typed into the TextField itself.
So the way it would work, is when someone types text into the a TextField, then tabs out of the field, the focusedProperty ChangeListener that I assigned will trigger where I can then take action on the text that the user typed.
Sure! Usually, the first parameter of listeners holds the source of the event. Cast it to the textfield type and you're done.
There is a more elegant way however. Since you have a custom class, provide it with a constructor that accepts the textfield that the listener will be handling. Assign it to a field and then when the event triggers you can access the field to get the source of the event without having to cast it.
What Stephan proposes in his second paragraph is a good solution (and it's probably the way I would do it too). However it creates one instance of the custom listener class for each TextField. But it seems that you want to create only one instance, and have it handle all of the TextFields. You didn't exactly say that you had that goal in mind, but if you did, I would just suggest it isn't really a worthy goal. Unless you have many thousands of TextFields, the memory used by creating one listener per TextField isn't worth worrying about.
Paul Clapham wrote:I would just suggest it isn't really a worthy goal. Unless you have many thousands of TextFields, the memory used by creating one listener per TextField isn't worth worrying about.
I sort of worked myself into that conclusion while I was waiting for a reply to my post. I always look for more efficient ways to code wherever possible, even if the time/value benefit doesn't exist. It's code for personal use so no real loss in the learning curve.
Curse your sudden but inevitable betrayal! And this tiny ad too!