The class which represent the model must extend Observable and implement the setChanged method.


public class Model extends Observable {

/*
Model implementation stuff goes here.
*/


// Notify observer classes that the model has changed.
public void updateView() {
setChanged();
notifyObservers((Object)new String("the model has changed"));
}

// The setChanged() protected method of the Observable class must be overridden to make it public.
public synchronized void setChanged() {
super.setChanged();
}
}

Whenever the contents of the model changes and you want to update the view call 'this.updateView()'.

The class which implements the view must implement Observer and must be added to the model's list of observers.

public class View implements Observer {
public void init() {
model = new Model();
model.addObserver(this);
}

// Observer interface update callback.
public void update(Observable o, Object arg) {
// update the view here
}
}


The above example isn't quite MVC. There should really be a Controller class which creates the model and the view. The controller should probably make the call to addObserver
eg.

model = new Model();
view = new View();
model.addObserver(view)

At least I think that's the way it should work. I find the MVC stuff a little confusing sometimes. I only learnt about it recently while learning to use Objective-C and the Cocoa frameworks on Mac OSX. It's basically an update of the old NextSTEP stuff. It was built from the ground up around the MVC paradigm and it does it really well. I've looked at the Squeak Smalltalk VM recently. I think Smaltalk might be where MVC originated. Trying to replicate that style of programming using an API that wasn't designed around MVC I think you need to make a lot of compromises.

I hope this is helpful.

Greg Hamilton

On Wednesday, February 26, 2003, at 07:31 PM, Rainer Öhman wrote:

Hi!
 
Following the MVC pattern, I'm trying to separate the swing gui from the data.
 
In the gui application I'm writing (moving users between LDAP trees), I would like to redirect the output produced by the class reading from LDAP to a JTextArea in the swing class - much like redirecting the System.out.println() to the JTextArea. This is an ongoing process, so each failure och success must be reflected in the JTextArea.
 
I understand that this involves some kind of listener, but how do I setup this kind of scenario?
 
Best,
 
- Rainer

Reply via email to