next up previous
Next: Lab Exercise 1: Editing, Up: In the Laboratory: Editing, Previous: Program Walkthrough: Class Definition

Program Walkthrough: Method Definition

The next element of the program is the init() method:


public void init()
{
    clickMe = new Button("Click Me Not!");   // Create the button
    clickMe.addActionListener(this);         // Activate the button
    add(clickMe);                            // Add it to the applet
}  // init()


The init() method is called once, automatically, whenever an applet is loaded into the Java Virtual Machine. Its purpose is to initialize the applet's interface and any variables used in the applet's processing. As the method's comments indicate, the method creates (new) a Button and adds it to the applet, which causes it to appear on the screen when the applet is run.

The actionPerformed() method is the last element in the program:


public void actionPerformed (ActionEvent e)
{
    if (clickMe.getLabel().equals("Click Me!"))
        clickMe.setLabel("Click Me Not!");
    else
        clickMe.setLabel("Click Me!");
}  // actionPerformed()


This method is called automatically whenever the applet's button is clicked. Its purpose is to ``perform action'' when a button-click event takes place. In this case the action it takes is to toggle the button's label from ``Click Me!'' to ``Click Me Not!'' or vice versa.



Ralph Morelli {Faculty} 2002-03-02