One way to write the listener class in
which you define the mouseClicked
method is to define the listener class as a
local class in the MovieApplication
class, as shown in the following
example, which also features a modification to a setter that calls the
addMouseListener
method, which the Meter
class inherits from
the Component
class.
The setMeter
setter is not as complex as the setMovie
setter
because setMeter
is called just once, whereas setMovie
is
called many times, once a choice list is added in Chapter 46,
import javax.swing.*; import java.awt.event.*; import java.util.*; public class MovieApplication extends JFrame { public static void main (String argv []) { new MovieApplication("Movie Application"); } // Declare instance variables: private Meter meter; private Movie movie; // Define constructor public MovieApplication(String title) { super(title); // Create model getMovie(); // Create and connect view to application getContentPane().add("Center", getMeter()); // Connect window listener, size and show addWindowListener(new LocalWindowListener()); setSize(300, 100); show(); } // Define getters and setters public Meter getMeter () { if (meter == null) {setMeter(new Meter(0, 30));} return meter; } public Movie getMovie () { if(movie == null) {setMovie(new Movie (10, 10, 10, "On to Java"));} return movie; } public void setMovie (Movie m) { if(movie == m) {return;} if(movie instanceof Movie) {movie.deleteObservers();} if(m instanceof Movie) { movie = m; movie.addObserver(new LocalMovieObserver()); movie.changed(); }} public void setMeter (Meter m) { meter = m; meter.addMouseListener(new LocalMeterListener()); } // Define observer: private class LocalMovieObserver implements Observer { public void update (Observable observable, Object object) { getMeter().setValue(getMovie().rating()); getMeter().setTitle(getMovie().getTitle()); } } // Define mouse adapter: private class LocalMeterListener extends MouseAdapter { public void mouseClicked (MouseEvent e) { int x = e.getX(); int y = e.getY(); int v = (int) Math.round(getMeter().getValueAtCoordinates (x, y) / 3.0); getMovie().setScript(v); getMovie().setActing(v); getMovie().setDirection(v); } } // Define window adapter private class LocalWindowListener extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); return; } } }