Applets - Part 3 -
Applets with Buttons & Key Press Events

bullet

In this example, we'll define and instantiate a button object, and then we'll use the action event handler (this is an inherited method from Applet, so we merely have to overload it)

bullet

Note, if you try this applet out, remember to change the applet name to "AppletWithButton.class" in the .htm file with the code parameter -
<APPLET CODE="AppletWithButton.class" ...

import java.applet.*;
import java.awt.*;

public class AppletWithButton extends Applet
{
    private Button button1 = new Button("Click Here!");
   
    // helper contains the text on button1 -

    // in this case, the String "Click Here"

    public boolean action(Event e, Object helper)
    {
        // TODO: Add your own implementation.

        // GENERATED BY J++: return super.action(e, helper);

bullet

Test to see if the event that occurred corresponds to button1

        if (e.target == button1)
        {
            setBackground(Color.green);
        }
        repaint();
        return true;
    }

bullet

Add the button1 object to the display when the applet is initialized using the init method.  Note, when no layout manager is specified, the default Flow layout manager is used ... it places controls on the display one after another going right, then down when necessary.
    public void init()
    {
        // TODO: Add your own implementation.

        // GENERATED BY J++: super.init();
        add(button1);
    }

bullet

We overload the keyDown event - we'll test what key was pressed, and change the background of the applet's display accordingly

    // keyDown doesn't belong to any one component
    // keyValue parm is the integer value of the key that is pressed
   
    public boolean keyDown(Event e, int keyValue)
    {
        // TODO: Add your own implementation.

        // GENERATED BY J++: return super.keyDown(p1, p2);

        switch (keyValue)
        {
        case 'r': setBackground(Color.red);
                break;
        case 'b': setBackground(Color.blue);
                break;
        case 'g': setBackground(Color.green);
                break;
        }
       
        repaint();
        return true;
    }
   
}   /* end of applet */

wpe4.jpg (22523 bytes)

Created & Maintained by DrB - Comments welcome.
Last edited on Friday, July 30, 2004