![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
All that remains is to define the observer
class, MovieDataObserverForTable
, that connects model changes to
the table.
The new observer checks all the movies to see which already are recorded in
the table; it adds all the movies that it does not find. It checks for
movies in the table with a private predicate, present
. One argument
of the private predicate is a vector of row vectors that you obtain using
getDataVector
; the first element of each such row vector is a movie
title.
When the observer does add a new row vector, each element in the row vector
must be a class instance; thus, int
values must be wrapped in
Integer
instances. JTable
procedures know how to deal with
both String
and Integer
instances, but they are flummoxed by
int
values, because only class instances can be tested for class
identity.
import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class MovieDataObserverForTable implements Observer { MovieTableApplication applet; public MovieDataObserverForTable (MovieTableApplication a) { applet = a; } public void update (Observable observable, Object object) { Vector movies = applet.getMovieData().getMovieVector(); RatingTable table = applet.getRatingTable(); RatingTableModel model = (RatingTableModel)(table.getModel()); // Check each movie for (Iterator i = movies.iterator(); i.hasNext();) { Movie movie = (Movie)(i.next()); String title = movie.getTitle(); // Ignore movie, if already in the table if (!present(title, model.getDataVector())) { // Add movie if not already in the table Vector row = new Vector(); row.add(title); row.add(new Integer(movie.rating())); row.add(new Integer(movie.getScript())); row.add(new Integer(movie.getActing())); row.add(new Integer(movie.getDirection())); // Add new row to the table model model.addRow(row); } } } // Test title to see if movie is in the data vector private boolean present (String title, Vector data) { // Iterate over all data elements for (Iterator i = data.iterator(); i.hasNext();) { // Each data element is a row vector Vector v = (Vector)(i.next()); // Title is first element of row vector String t = (String)(v.firstElement()); if (t.equals(title)) { return true; } } return false; } }