Chapter 14: Widget Wizardry

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


  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.


  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 (new Button("A Nickel"));
        int i = 1;
        String nextline;
        fortunes = new Vector();
        while ((nextline = getParameter("fortune" + i++)) != null) {
      public boolean action(Event e, Object o) {
        if ( 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
Last Modified August 23, 1996