Search code examples
eventsjavafxjavafx-8listenereventhandler

Triggering calculation for specific textfield when other textfields change


I'm new to JavaFX and I would like to do the following:

Whenever the value of one of my four textfields is changed, I would like a fifth textfield to calculate the sum of the values from the others. Lets assume the values come already as numbers.

Code looks like this:

power1KW = new TextField();
power2KW = new TextField();
... etc.
powerSumKW = new TextField();

How do I do this properly? Do I add a ChangeListener on each of my powerXKW-TextFields? And calculate on change?

Or do I need to add an EventHandler for my powerSumKW-Textfield? How can I handle the Event fired only by the powerXKW-TextFields?

Any advice would be appreciated. Thank you!


Solution

  • I would just bind the textProperty of the 5th Textfield to the other textfields..something like this:

    tf5.textProperty().bind(Bindings.createStringBinding(()->{
               //Do your calculation
               //Return result as String
               return result;
            }, tf1.textProperty(),tf2.textProperty(), tf3.textProperty(), tf4.textProperty()));