Different Ways to Run Applet in Java
Applets are tiny Java programs that can be installed and run automatically as part of a web page. They can be viewed on an Internet server, transmitted over the Internet, and installed and run automatically as part of a web document or desktop application.
There are two standard methods for running an applet:
- By using Web Browser
- By using Applet Viewer
Let’s understand each technique one by one
1. Executing the applet within a Java-compatible Web browser:
Suppose we have a GfgApplet.java file in which we have our java code.
- Compiling: javac GfgApplet.java
- Create an Html file and embed the Applet tag in the HTML file.
To run an applet in a web browser, we must create an HTML text file with a tag that loads the applet. For this, we may use the APPLET or OBJECT tags. Here is the HTML file that runs HelloWorld with APPLET:
Attributes in applet tag:
- Code: It specifies the name of the applet class to load into the browser.
- Width: It specifies the width of an applet.
- Height: It sets the height of an applet.
<html> <body> <applet code="GfgApplet.class" width=300 height=100></applet> </body> </html>
Output on browser:
The applet GfgApplet.class is loaded into the browser when you access GfgApplet.html.
To load applet programs, the browser must have java enabled.
2. Using an Applet Viewer to run the applet:
It is a java application that allows you to view applets. It’s similar to a mini-browser that will enable you to see how an applet might appear in a browser. It recognizes the APPLET tag and uses it during the creation process. The APPLET tag should be written in the source code file, with comments around it.
- Write HTML APPLET tag in comments in the source file.
- Compile the applet source code using javac.
- Use applet viewer ClassName.class to view the applet.
To use the applet viewer utility to run the applet, type the following at the command prompt:
c:\>javac GfgApplet.java c:\>appletviewer GfgApplet.java
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.