Chapter 14: Widget Wizardry

The exercises here are taken from my forthcoming book, The Java Developer's Resource.

Quiz

  1. What is the purpose of an action method?

    The action method lets you handle the activation of a component, i.e. a user action directod at a widget.

  2. When is the action method called?

    Any time an event occurs in a Component.

Exercises

  1. Modify the fortune teller applet so that it reads the fortunes out of an indefinite number of PARAM tags and randomly selects the fortune.
    
    import java.applet.Applet;    
    import java.awt.Label;
    import java.awt.Button;
    import java.awt.Event;
    import java.util.Vector;
    
    
    public class Fortune extends Applet {
    
      Vector fortunes;
      Label l;
    
      public void init() {
        l = new Label("Your Fortune for a nickel");
        add(l);
        add (new Button("A Nickel"));
        
        int i = 1;
        String nextline;
        fortunes = new Vector();
    
        while ((nextline = getParameter("fortune" + i++)) != null) {
           fortunes.addElement(nextline);
        }
    
      }
      
      public boolean action(Event e, Object o) {
      
        if (e.target instanceof Button) changeFortune();
        return true;
        
      }
    
      public void changeFortune() {
      
        int i = (int) (Math.random() * fortunes.size());
      
        l.setText((String) fortunes.elementAt(i));
        
      }
    
    }
    


[ Exercises | Cafe Au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ]

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
Last Modified August 23, 1996