propertyChangeListeners chain reacting, causing overflow

197 Views Asked by At

Just a snippet of code. Doing a project for class where I have to convert Celsius, Fahrenheit and Kelvin based on a change to their respective JFormattedTextFields. The problem is that when the listener reacts to the change in Celsius, my program changes Fahrenheit, which then reacts to my Fahrenheit listener, which reacts my Celsius listener again, and so on. I haven't worked in my Kelvin stuff yet due to this problem. I doubt my code is needed, since this is more of a conceptual problem, but here it is anyway:

private class ValueChangeHandler implements PropertyChangeListener
{
    public void propertyChange(PropertyChangeEvent event) 
    {

        Object celsiusChange = event.getSource();
        Object fahrenheitChange = event.getSource();
        Object kelvinChange = event.getSource();
        if(celsiusChange == celsiusField)
        {

            tempCelsius = (Double)celsiusField.getValue();
            tempFahrenheit = celToFah(tempCelsius);
            tempKelvin = celToKel(tempCelsius);
            fahrenheitField.setValue(tempFahrenheit);
            kelvinField.setValue(tempKelvin);

        }

        else if(fahrenheitChange == fahrenheitField)
        {

            tempFahrenheit = (Double)fahrenheitField.getValue();
            tempCelsius = fahToCel(tempFahrenheit);
            tempKelvin = fahToKel(tempFahrenheit);
            celsiusField.setValue(tempCelsius);
            kelvinField.setValue(tempKelvin);

    }
}
1

There are 1 best solutions below

0
On

A PropertyChangeEvent is fired only if the new value is not equals to the previous one. So i suppose there is a problem with your celToKel and fahToKel.

For example, converting a celsius tempature C1 in Fahrenheit and again in Celius results in a C2 which is not equals to C1.

Another solution could be to remove the listener before setting the value and to add it again after.

public class ValueChangeHandler implements PropertyChangeListener
{
    @Override
    public void propertyChange(final PropertyChangeEvent event)
    {
        ...
        fahrenheitField.removePropertyChangeListener("value", this);
        fahrenheitField.setValue(tempFahrenheit);
        fahrenheitField.addPropertyChangeListener("value", this);
        ...
    }
}

Checks also that your listener is bound only to the value property

fahrenheitField.addPropertyChangeListener("value", this);

and not to all the properties

fahrenheitField.addPropertyChangeListener(this);