How to compile and run Java applet code

The Java programming language can be used to write applets that run in a browser. Applet source code is similar to a typical Java program source code, except that it does not have a main method. Applet source code can be created in .java files.

Compiling them is the same as usual:

$ javac

This generates a foo.class compiled bytecode file.

However, running the generated .class file using the Java VM gives this error:

$ java foo
Error: Main method not found in class foo, please define the main method as:
   public static void main(String[] args)

Applet can only be executed in a browser by opening a HTML file that refers to this applet .class file. A minimal HTML file that does is:

<applet code=foo width=400 height=200>

Save this as foo.html file in the same directory as the foo.class file. Open it in a browser that can run Java applets and you can see the result. 🙂

Tried with: Java 1.7, Firefox 34 and Ubuntu 14.04


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.