Brandon Rozek

Thoughts on Web Development, Statistics, and Linux

Viewing Java Applets

When you use an IDE there are many things you can take for granted. A section of an intro level computer science course at my university uses JGrasp to build Java Applets.

Following around using a normal text editor, I found that I couldn’t just compile and run the code like I have with my java programs in the past. To be able to help around and assist in the course, I need to be able to build and run these applications. The rest of this article describes the process I underwent to be able to use my existing setup to write and build java applets. Of course you can always install JGrasp and have that all built in, but it’s always nice to not have to change your workflow.

When I tried following along, I would receive the following error

Main method not found in class HelloWorld, please define main method as...

Which makes sense since I have never defined a main method inside my source code. So how do I go about doing this?

Setup

Java Applets are meant to run on web pages, because of this one needs an html file to host the applet. The following code gives you the bare minimum for setting up the html file. I called it HelloWorld.html.


<html>
    <head><title>Applet Container<title>
    <body>
        <applet code='HelloWorld.class' width=400 height=400></applet>
    </body>
</html>

Hello World Program

To get it up and running, I will show a “Hello World” like application for applets.


import javax.swing.JApplet;
import java.awt.Graphics;

public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
        g.drawString("Hello World", 30, 30);
    }
} 

Running the Applet

Now we need to compile the code

javac HelloWorld.java

Then run the appletviewer

appletviewer HelloWorld.html

Conclusion

This tutorial concludes the setup of running a simple Java applet. From here you can look at the different methods in the Graphics library and play around 😀