Another Hello World applet

This applet look a little bit better:

import java.applet.*;
import java.awt.*;
This time we import the entire java.awt package, this way we can use all the classes in the awt package.
 
public class HelloWorld2 extends Applet{
     //Declare objects
     String text;
     Font font;
In addition to the String object, we declare an object of the class Font (you can call it whatever you want to as long as it is a Font object).
public void init(){

     text="Hello World";
     font=new Font("Helvetica",Font.BOLD,24);

     setBackground(Color.black);
 }

Here we also initializes the Font object by calling its constructor with new. The Font constructor takes three arguments. The first is a String, this String must be a font that java recognise, I use the font Helvetica. The second one is an int, here I use a predefined int from the class Font. You can use BOLD, ITALIC or PLAIN, this defines the style of the font. The last one is also an int, and it describes the size.
public void paint(Graphics g){

    //Draws a nice frame for the String
    g.setColor(Color.blue);
    g.fillRect(20,20,160,60);
    g.setColor(Color.red);
    g.fillRect(25,25,150,50);

I'll do this method in 2 pieces, this 1st piece draws a nice frame for the String. First it uses the predifined color blue and asign it to the Graphics object. Then it draws a filled Rectangle in this color. Next it sets the color red, and draws a filled rectangle in this color. This last rectangles upper left corner is 5 pixels below and 5 pixels to the right of the first one, and it is 10 pixels smaller each way. This way the blue frame around the red rectangle will be 5 pixels.
    g.setFont(font);
    g.setColor(Color.white);
    g.drawString(text,33,58);

    }
}

Here is the other part. The first thing we do is to asign the font we declared to the Graphics object, that way we can draw the string in this font. Next we set the color to white, so we can draw the text in white color. Last we draw the string in position (33,58) to center it within the applet and close the class.

Now just compile it, write the html file and run it. Or check it out   here.

 Return to the homepage