Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

The Observer Pattern and JTable/Abstract Table Model

Model-View Separation
1. Keep model (data) code as separate as possible from view (gui) code
2. View knows about model, but model doesnt (explicitly) know about view.
class CatalogApplet
{
public CourseList courseList;
public onEvent(..)
{
// gather data
// modify model (e.g., courseList)
// update view
}
class CourseList
{
// no reference to applet
Reason we can easily port model to a different GUI
Sometimes we have multiple views of model
Catalogs courseList appears in CatalogView and SchedulerView
If model is updated, need to notify all views.
But Model isnt supposed to know about view???
Observer Pattern (see Gamma p. 293)

We let model have an abstract or generic list of observers


Not tied to any concrete observer (so doesnt hurt porting)

AbstractTableModel
(Data)

TableModelListeners

When the model is modified, it automatically notifies all observers in list


Example: Keep track of a list of students, where each students has name and id.
StudentList viewed in a JTable
Using JTable and AbstractTableModel
1. Draw a JTable using the visual composition editor.
2. Define a concrete subclass of AbstractTableModel, e.g.,
class StudentTableModel implements AbstractTableModel
3. Override AbstractTableModels abstract methods:
int getRowCount();
int getColumnCount();
Object getValueAt(int row,int col);
4. Graphically connect the JTables model attribute to youre StudentTableModel

AbstractTableModel

JTable

ModifyData()
fireTableDataChanged()

tableChanged()
getRowCount()
getColumnCount()
getValueAt(row,col)

Observers need only know how to update themselves.


public interface Observer
{
public void update();
}
Model needs to track observer list and notify observers when change
public class Model
{
List observerList; // made up of Observer
void attach(Observer o)
{
}
void detach(Observer o)
{
}
void notifyObservers()
{
// loop through and call update on all
}
// some methods that modify data in Model
void modify1()
{}
void modify2()
{}

}
class ConcreteObserver implements Observer
{
public void update()
{ // get some data from model, redraw self}
}
Note that Model isnt coupled with any concrete observers, so portability not a
problem.

AbstractTableModels abstract methods:


int getRowCount();
int getColumnCount();
Object getValueAt(int row,int col);
Using the JTable framework
1. Write a subclass of AbstractTableModel. Have it point to your data (e.g.
CourseList)

2. Link your model to a JTable (or many JTables)


3. Add a call to fireTableChanged() in appropriate places of your model.

You might also like