Re: Model View Controller The Farenheit GUI follows. It defines listeners and adds them to its components using the addlistener methods defined in the superclass. It also supplies the update method. The Celsius one is similar. Its only difference is that it uses getC and setC instead of getF and setF.
The key to this is the update method of the Observer interface. This is called by the model when it executes the notifyObservers method. Each registered observer is sent an update message. The view responds by querying the model for changed information and then updating itself accordingly. Here we get the new temperature in the desired units and set the display accordingly.
The action listeners also update the model by calling its mutators. This lets the user, who sees the view, manipulate the model itself. Note, however, that the listeners don't update the view's display. Instead they wait for the update message that they know will be sent by the newly changed model.
class FarenheitGUI extends TemperatureGUI
{ public FarenheitGUI(TemperatureModel model, int h, int v)
{ super("Farenheit Temperature", model, h, v);
setDisplay(""+model.getF());
addUpListener(new UpListener());
addDownListener(new DownListener());
addDisplayListener(new DisplayListener());
}
public void update(Observable t, Object o) // Called from the Model
{ setDisplay("" + model().getF());
}
class UpListener implements ActionListener
{ public void actionPerformed(ActionEvent e)
{ model().setF(model().getF() + 1.0);
}
}
class DownListener implements ActionListener
{ public void actionPerformed(ActionEvent e)
{ model().setF(model().getF() - 1.0);
}
}
class DisplayListener implements ActionListener
{ public void actionPerformed(ActionEvent e)
{ double value = getDisplay();
model().setF(value);
}
}
}
It is important to notice that the view does not hold any information internally about the current temperature in the model. This way it is never "out of date." It can always get the current temperature by querying the model.
__________________ Thanks & Regards, Jegan CBK "We will either find a way, or make one!” |