tags:

views:

337

answers:

3

I am currently working on a project in which I have a Java GUI class and another class which contains its relevant methods.

I want a text area in the GUI to be updated with the content of a string in the other class whenever it changes. What is the easiest way to watch for these changes?

Cheers!

+3  A: 

You're looking for data binding. Java unfortunately has no own support for that, but there are several libraries to choose from, like for example JGoodies data binding.

If you want to roll your own, there's the ubiquitous observer pattern which you doubtless already know from Swing :). Just add listener support to the class holding the strings and add a listener to it that updates the text area, when an event comes.

Joey
+1  A: 

Make the "other class" a proper bean that supports PropertyChangeListeners. Then create a PropertyChangeLister which racts on changes in the "other class" and which updates the textarea.

Somethin like this:

otherClass.addPropertyChangeListener("propertyname", new PropertyChangeListener() {
   void propertyChange(PropertyChangeEvent evt) {
     textarea.setText(evt.getNewValue());
   }
}

See

http://java.sun.com/j2se/1.4.2/docs/api/java/beans/PropertyChangeListener.html

http://java.sun.com/j2se/1.4.2/docs/api/java/beans/PropertyChangeSupport.html

http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html

ordnungswidrig
A: 

Have a look at BeansBinding

It does almost exactly what you need. Only thing is that your otherClass must support Java Beans listeners, as described by @ordnungswidrig

Ayman