How to Make a Java Applet

by Aseus in Circuits > Websites

10877 Views, 11 Favorites, 0 Comments

How to Make a Java Applet

write_run_java_program_helloworld_example.png

This instructable will guide you on how to make a Java applet. The applet will output a simple message displaying "Hello World".

Java IDE

Download an IDE to write Java code. Skip this step if you already have one.

Note: I will use Eclipse for this instructable, but any IDE should be ok.

Make a New Java Project

s2a.png

Before starting to write code, you have to make a new Java project.

Name the Project

You can give it any name, I'll name it Hello World because that's the output we'll get.

When you finished typing the name, click on the Finish button.

Make a New Class

s4a.png

Make a new class and then name it. Remember that the class name and file name must be the same.

Import Java.awt.* and Javax.swing.*

s5a.png

On top of the code, type import java.awt.*; and type import javax.swing.*;

This will import the packages and the asterisk will tell the compiler to look for every class in a package.

Extends JApplet

s6a.png

Type extends JApplet after the class name. This is to specify that the class is an applet and the class will inherit the functionality of an applet.

Make the Paint Method

s7a.png

The paint method is where the "main" code of the applet will be written. We need a method that has an argument object from the Graphics class. The object is usually written as g. The method will be public and won't return anything.

Add Super.paint(g); in the Paint Method

s8a.png

Type super.paint(g); in the paint method. This will force the applet to draw itself before drawing anything else, so that the output will be displayed correctly.

Code to Display the Message

s9a.png

Now the only thing left is to write the code to display Hello World in the applet. We will call a method called drawString which will take a string, x and y values as parameters respectively. To write the string, it will be surrounded by double quotation marks; and the x and y values have to be an integer. We can choose any x,y value as long as it's not 0,0. If we choose 0,0; then the string will not be visible, as it will be above the visible area.

I will choose as x value 20 and y value 20.

The code will be: g.drawString("Hello World",20,20);

Note: There are no negative values for x and y.

Output

s10a.png

Finally, click on the Run button and you will see an applet viewer window with the string Hello World.

Congratulations! You made an applet.