In our first Java applet, we will draw a cross on the screen.
Step 1 - Write your applet
Open Notepad and copy and paste the following code:
| //Java applet to draw a cross on the screen //created by M Meijers June2005 import java.awt.Graphics; |
Save it as FirstApplet.java
![]() |
|
Step 2 - Compile it
- Open a command window
- Change directory to the one where your applet is saved.
- Type javac FirstApplet.java
- Make sure it compiles without errors.
Step 3 - Create a Web Page for your applet
Applets must live within a web page, so we will create one.
Open Notepad and type in the following html:
| <html> <body> <applet code=FirstApplet.class width=200 height=200> </applet> </body> </html> |
This will insert your applet into a 200x200 pixel area on a web page. Save it as cross.htm
Step 4 - View your page
Open your cross.htm file in your web browser
or alternatively, in your command window type: appletviewer cross.htm
Appletviewer is an application that comes with Java that enables you to quickly check your applets, without have to open your web browser.
![]() |
|
More Methods
There are plenty of methods available for the Graphics class. If you want to see all the methods available for the Graphics class, you can look in the Java documentation. It should be located in the folder where Java is installed in docs\api\java\awt\Graphics.html
Here is another program for you to experiment with. It uses the fillRect method which has 4 parameters. The first two are the x and y coordinates of the top left corner, and the second two are the width and height of the rectangle in pixels. The setColor method is used to set the colour.
| //Java applet to draw coloured boxes //created by M Meijers June2005 import java.awt.Graphics; import java.awt.Color; public class FirstApplet extends java.applet.Applet { public void paint(Graphics g) { g.setColor(Color.blue); g.fillRect(0, 0, 200, 200); g.setColor(Color.red); g.fillRect(25, 25, 150, 150); g.setColor(Color.green); g.fillRect(50, 50, 100, 100); g.setColor(Color.yellow); g.fillRect(75, 75, 50, 50); } } |
Some other methods you might like to try are:
drawOval(x, y, width, height) (where x,y are the coordinates of the top left corner, and width and height in pixels)
fillOval(x, y, width, height)
drawString("Hello", x,y) (where x, y are the coordinates where the string will start)
![]() |
|
![]() |
|




