next up previous
Next: 3.2 What is Concurrent Up: 3.1 GUI Programming Previous: 3.1.3 How to Write

3.1.4 How to Write a Controller

From a programming perspective, the controller is the most interesting part of this example. It glues together the model and view using callbacks and then terminates. Of course, whenever the view receives an event, it invokes callbacks, code defined in the controller, to process them. The controller's callback code performs whatever updates are required to the model an to the view.

public class ClickCounterControl extends JApplet {
  
  // ** fields **
  private ClickCounter counter;
  private ClickCounterView view;

  // ** constructors **
  // relying on default constructor

  // ** methods **
  // relying on inheritance from JApplet

  public void init() {
    counter = new ClickCounter();
    view = new ClickCounterView(this);
    view.setMinimumState();
    view.setValueDisplay(counter.toString());


    view.addIncListener(new ActionListener(){
      public void actionPerformed(ActionEvent event) {
	if (counter.isAtMaximum()) return;
	if (counter.isAtMinimum()) view.setCountingState();
	counter.inc();
	view.setValueDisplay(counter.toString());
	if (counter.isAtMaximum()) view.setMaximumState();
      }
    });
      
    view.addDecListener(new ActionListener(){
      public void actionPerformed(ActionEvent event) {
	if (counter.isAtMinimum()) return;
	if (counter.isAtMaximum()) view.setCountingState();
	counter.dec();
	view.setValueDisplay(counter.toString());
	if (counter.isAtMinimum()) view.setMinimumState();
      }
    });

    view.addResetListener(new ActionListener(){
      public void actionPerformed(ActionEvent event) {
	counter.reset();
        view.setMinimumState();
        view.setValueDisplay(counter.toString());
      }
    });
  } 
}



Corky Cartwright
2000-01-07