Lesson 2:

A simple Applet:

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

// The Hello class simply displays the string "Hello, world!"
// within the graphics object.

public class Hello extends Applet
{
   public void paint(Graphics g)
   {
      g.drawString("Hello, world!", 20, 10);
   }
}
  1. Importing classes that are already defined in Java.  
    Classes must be imported before you can use them.  We are importing the applet and awt packages.
  2. Defining our own class  
     We are defining our own applet which inherits everything from the Applet class:

    public class myClassName extends Applet
    {
       // ...
    }
  3. Defining our own method
    Within our applet we define a method  paint which is used to draw the applet on the screen.  A method is defined as follows.

    visibility returnType methodName(formal argument list)
       {
          ...statements...
       }


    a. The visibility specifier can be either public or private to indicate whether method can be used outside the class or not.
    b. The returnType indicates what kind of value is produced by the method.   The  specifier  void means that the method does not return a value
    c. The formal arguments are input values to the method. ( paint takes one argument which is a Graphics object)
  4. The body of the paint method
    The paint method changes the Graphics object  g  to specify how the Applet should be drawn.

 

Try this:

  1. Copy the file Hello.java from the course web page.  Create a project and try it out.
  2. Add another statement to the body of the paint method which displays your name somewhere in the applet.
  3. Look at the documentation for the Graphics class and see if you can draw a Rectangle somewhere in the applet.
  4. Create a Color object in the paint method with any red, green, and blue values that you want (Do we remember how to do this from lesson1?).  Look up the  documentaion for the setColor method in the Graphics class.  Use this method at the start of paint with your Color object as its argument and see what happens.