Java meets the Energizer Bunny

Programming attributes and properties into animated icons -- plus a reader contest

It keeps going, and going, and going, the advertising jingle persistently chants. If there ever was an advertising campaign ideally suited for the World Wide Web, the Energizer Bunny is it! This silly, battery-operated character could easily be brought to life on the Internet if a few brave Java coders put their minds to it.

Without question, the Internet has become a viable, new medium for corporate marketing and promotion -- a new way for advertising agencies and their clients to divert marketing dollars away from their radio, print, and TV budgets.

Whether you're a marketer or a technologist, here in The Cyberstruction Zone we'll explore the hottest paradigm-shift-of-the-month for online developers who want to author Web content for online marketing and commerce. As your host, I will do my best to challenge us each month with playful projects that sharpen our talents and tools.

Welcome to The Cyberstruction Zone

As a "closet techie" who remembers CP/M, 16 KB RAM, external switches, and the S-100 bus with great respect and humility, I must confess that I am a joiner. I have jumped onto every technology bandwagon from expert systems to C.A.S.E. to client/server networking.

Today, I am in love with the World Wide Web.

Whether your company sells pizza, pipes, or pop rockets, exciting opportunities exist today for talented developers, smart consultants, and anyone with a little curiosity and vision.

Many companies who want to put up a home page are praying that their local Webmaster will know what to do. Yet a growing number are willing to take the extra time to reevaluate how their old business must change in order to be profitable on the Web.

Let's build some barns together in cyberspace! Each month here in The Cyberstruction Zone we will not only share technical ideas, we will exchange hammers and nails with actual, ready-to-use code.

Cyberstruction Challenge 1: Building a branded icon

In this first column, let's create an animated icon with Java (complete with music, speech, and sound effects) that could be used as a branded character like Mickey Mouse, the California Raisins, or the Energizer Bunny for an online marketing campaign.

Rather than infringe on another company's trademark, your challenge is to invent a brand of your own. For now, let's call him Billy the Bouncing Bean.

After you've invented your own Billy, given him some brains, and added a little humor perhaps, you can let him loose on your Web site.

Via e-mail and a dedicated Web page, I will referee and judge the best applets and code samples from the swiftest Java Jockies. Only the best will be posted to The Cyberstruction Zone's special Web site, where they will be presented for the rest of us to study.

In the manner of pop music radio and David Letterman, winners will jockey for position in the "CZone Top Ten" for each contest, and archives will be maintained historically on every contest. An online database "voting engine" will enable silicon surfers to dislodge the current King of the Hill and send him tumbling down the list.

Of course all worthy challenges must have a deadline. Our Billy the Bouncing Bean's deadline is officially set as 12 a.m., April 1, 1996 (how about an April Fool icon?). On this day, whoever's code survives and remains King will get a killer prize that will make the whole experience worthwhile!

Now, let's get down to brass tips.

Tip 1: Communication between animated applets

According to Steve Alexander (one of the founders of a hot new Java shop called Digital Focus), it is possible to get two or more animated applets to talk to each other.

In other words, you can get Billy to talk to Betty ... that is, if she'll even listen to him!

Getting two (or more) animated applets to talk to each other is an interesting way to add some "intelligence" to a Web page. One way to accomplish this is by getting a handle to another applet with:

getAppletContext().getApplet("name")

where "name" is the name of the applet set in the HTML parameter.

To make things more interesting, you can build a background class which uses static variables. No matter how many times the class is instantiated, these static variables will have only one copy in memory.

Here's an example:

1. Build a mediator class which contains the static variables. This class will be called by other applets so there is no need to extend it from the applet class:

class Mediator
{
    private static int newIndex=0;
    private static int oldIndex=0;
    //Retrieves the static variable
    public int getIndex()
    {
        return newIndex;
    }
    //Sets the static variable (for all applets)
    public void setIndex(int n)
    {
        oldIndex = newIndex;
        newIndex = n;
    }
}

2. Build your animation applet and call the mediator class:

public class myApplet extends Applet implements Runnable
{
    Mediator myMediator;
    public void init()
    {
        //Make a new copy of the Mediator class
        myMediator = new Mediator();
    }
    public void run()
    {
        //If the Mediator index is even...
        if((myMediator.getIndex()%2) == 0)
        {
            //do something with animation
        } else
        {
            //do something else
        }
    }
}

Next, build your second applet (which will use setIndex() to change the static variable). When the second applet varies the static index, the first applet will react based upon the number set by the second applet. The net result: the applets appear to send data from one to the other.

This is a simple example. As you add complexity (by sending data in two directions, for example) you will need to add additional checks to ensure that data is read and written in a synchronous manner.

Tip 2: Fetching content from a Web server

This code sends an http server a request for an object, and passes the content back to the browser to process it like an HTML (or any other kind of) page:

// Open the URL and display it as a new page
try {
    String NLinkname = "http://home.netscape.com";
    URL NLink = new URL(NLinkname);
    MYAPPLET.getAppletContext().showDocument(NLink);
}
catch(java.net.MalformedURLException e) {
    System.out.println("Malformed URL!!!! exception");
}

(Submitted to The Java Developer by Daryoush Mehrtash. Note: The Java Developer URL is http://www.digitalfocus.com/faq and should not be confused with JavaWorld's column of the same name.)

Tip 3: An application/applet

The following class would run as an application/applet. Of course, if you're going to run this as an applet, you will need to supply an appropriate HTML file reference. Wherever you want it, it should read as:

<applet code="easyOne.class" width=300 height=300>
</applet>

Now, here's the actual Java code:

import java.awt.*;
import java.applet.*;
public class easyOne extends Applet
{
    public void init() {
    }
    public void resize() {
       resize(300,300);
    }
    public easyOne() {
       setLayout(new BorderLayout());
       Panel p1 = new Panel();
       p1.setLayout(new FlowLayout());
       add("South", p1);
       p1.add(new Button("ButtonOne"));
       p1.add(new Button("AnotherButton"));
    }
    public void paint(Graphics g) {
       g.setColor(Color.cyan);
       g.drawRect(10,10,150,150);
       g.fillRect(10,10,150,150);
    }
    public static void main(String args[]) {
       Frame f1 = new Frame("Standalone Application");
       easyOne s1 = new easyOne();
       s1.init();
       s1.start();
       f1.add("Center", s1);
       f1.resize(300, 300);
       f1.show();
    }
}

(Submitted to The Java Developer by Vivek Pabby)

Tip 4: Sending your browser to a new location

Here's how you have your applet send the browser to a new location:

/*** Load URL.*/
public boolean loadUrl() {
    urlLoaded = true;       // well, tried to load anyway
    if (url == null)
    return false;
    dbg("loadUrl()");
    // use showDocument() to display new URL.
    // Note: Netscape 2.0b2 problems here... I don't really
    // understand how to catch errors from showDocument()!
    try {
        getAppletContext().showDocument(url);
    }
    catch (Exception e) {
        if (url.getRef() == null) {
            errMessage = "Couldn't load url. :-(";
        }
        else {
            errMessage = "Couldn't load url: " + url.getRef();
        }
        return false;
    }
    return true;
}

(Submitted to The Java Developer by William S. Clark)

Java Billy Contest tools & rules

It's a simple task, really.... All you have to do is provide the tightest, most elegant Java code sample that satisfies as many of the following criteria as possible in the Java Billy judging process:

Criteria 1: Originality in animated icon branded characterization (e.g., humor, communication, etc.)

Criteria 2: Automated or random navigational capabilities (wandering around, onto, and off of Web pages)

Criteria 3: Automated or random sound file generator (use RealAudio, Xing, or your favorite format)

Criteria 4: Intelligence of attributes and properties (like automated follow-the-mouse, agent-like user interaction, multiple icons that "learn," icons with parts that come apart and reassemble, user-triggered sound and/or animation events, etc.)

Criteria 5: Database hooks (e.g., allowing icons to evolve with dynamic, interactive features)

Criteria 6: Commerce functions permitting your Billy to sell you things

Criteria 7: E-mail, chat, "graffiti wall" or other communication-related features

Criteria 8: FTP provisions for user downloading of additional resources

Let the Billy Wars begin!

OK, so I lied. Building a sophisticated Java Billy is no small task. Yet the robust feature set of the Java language provides the functionality to build some amazing applets! So sharpen your wits, have fun with the graphics, cleverly compress your sound files, and code away!

Next month in The Cyberstruction Zone we'll extend Billy's powers by exploring rapid prototyping in Macromedia Director/Shockwave with "plumbing extensions" in Java.

As chairman of Cyberstruction Inc., Craig LaGrow serves a small number of Fortune 500 clients and advertising agencies by creating customized, turnkey WWW solutions ("Online Technology Implementation Plans") that implement advanced, emerging Web technologies. (c) Syndicated material published by 1996 Cyberstruction, Inc.
Related: