Search code examples
javaobserver-patternjtextfield

Observer Pattern for JTextField?


Suppose I have a class:

class Boy
{
      int age = 25;
}

I have a JTextField, age, that updates the 'age' instance field of Boy. Alternatively, if the age of the boy is changed another way (perhaps, setAge() ), I need to be able to reflect this change in the JTextField.

Using the observer pattern is one way. In this case, am I forced to create a new class JTextFieldThatObserves (which inherits from JTextField and implements Observer)

Is the default JTextField incapable of doing what I need it to do?


Solution

  • Java does not ship with an automatic binding framework for Swing components and an object's fields. This is one of its major flaws!

    I'm afraid the only mechanism to do this is to use the observer pattern on both the widget and the object and watchful of infinite cycles.

    One thing useful in these cases is a PropertyEditor as it saves you from creating a gazillion different listener/event classes.