top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Applet in Java

Introduction

Understanding the applet in Java is integral to the world of modern programming. Applets are a unique Java program that runs on web pages, providing interactive features that enrich the user experience. However, the back-end technology might seem complex and intimidating, especially to newbies.

This comprehensive guide aims to explore Java applets, starting from the basics and gradually climbing up to the intricate details. We'll explain why applets are pivotal, how to write them, and their role in web-based applications. Both beginners who have just embarked on their Java journey and seasoned coders aiming to refresh their knowledge will find this guide helpful.

By delving into the practical aspects of the applet in Java, we hope to bridge the gap between theory and real-world application. After all, theoretical knowledge shines brightest when applied in practice. Now, let's step into this enthralling realm of Java applets, where every line of code can potentially reshape web interactivity.

Throwback to Making a GUI Application

Coding GUI applications was a significant leap in technology, adding a user-friendly interface to the mix. An integral part of this evolution was understanding and utilizing the applet life cycle in Java. This cycle, a set of stages an applet goes through from initialization to destruction, shaped how we designed and interacted with GUI applications.

Creating the applet in Java introduced us to an exciting world of interactive web applications where code wasn't just executed - it lived. The applet life cycle defined this 'living' journey, driving the application through various stages. From being born (initialization) to growing (starting), pausing when needed (stopping), and finally, when the purpose was served, gracefully ending its course (destruction).

This applet life cycle in Java formed the backbone of our GUI applications, guiding us to build robust, responsive, and reliable software. By mastering it, we could ensure our applications performed efficiently, behaving as expected at each stage.

What Is Applet in Java?

An applet in Java is a unique type of Java program designed to be embedded within a web page, enhancing the interactive capabilities of the webpage. The applet in Java runs on the client side, making web pages more dynamic and interactive.

It provides powerful functionalities ranging from animation and gaming to complex computational solutions.

Types of Applet In Java

The applet in Java can be broadly classified into two categories:

1. Local Applets: These are applets that exist on the same device as the one where they are executed. They have unrestricted access to resources on the user's device. Yet, this type of applet is less common due to security concerns.

2. Remote Applets: These applets reside on a different machine (typically a server) and are loaded over the network into the user's device for execution. Due to security reasons, they run in a restricted environment (sandbox) and have limited access to the user's system resources.

Creating A Basic Applet in Java

We'll now craft a simple program that displays a line of text, serving as an example of Java applet programs.

1. Write the Java Applet Code

Create a new Java file and paste the following code:

This code creates an applet that will display the text "Hello, Applet World!" at the coordinates (20, 20).

2. Compile the Applet

Use the javac command in your terminal or command prompt to compile the file:

This command generates a HelloWorldApplet.class file.

3. Create an HTML File to Host the Applet

Now, you need an HTML file that can call the applet:

Save this HTML file in the same directory as your .class file.

4. View the Applet

Open the HTML file in a web browser with Java enabled or use the applet viewer tool that comes with the JDK:

When you run this program, the output will be a new window displaying the string "Hello, Applet World!" at the specified coordinates. It stands as a simple yet effective example of Java applet programs with output.

Adding User Interface Elements to Your Applet

In addition to basic graphics, the applet in Java can also include user interface elements like buttons, text fields, and checkboxes. Here's how you can add them:

1. Write the Java Applet Code

Create a new Java file, import the necessary packages, and add the UI elements within the init() method of your applet class:

This code creates an applet with a button that says "Click me" and a text field for input.

2. Compile the Applet

Use the javac command in your terminal or command prompt to compile the file:

This command generates a UIApplet.class file.

Running Your Applet in a Web Browser

After adding UI elements to your applet, you need to run it. To do this in a web browser, follow these steps:

1. Create an HTML File to host the Applet

Save this HTML file in the same directory as your .class file.

2. Open the HTML file in a web browser with Java enabled:

When you run this program, the output will be a new window displaying the button and text field within the specified coordinates.

Life Cycle Of An Applet

An applet has four life cycle methods:

1. init()

This method is called only once during the life cycle of an applet, specifically when the applet is first loaded. It's used for initialization purposes - setting up variables, loading images or files, setting up the GUI, etc. It's akin to the "birth" of the applet.

2. start()

This method is used after the init() method. Every time the applet is restarted, for instance, when a user revisits the webpage containing the applet. In this method, you'd put code that starts or resumes processes (like animations or computations) that should run when the applet is visible.

3. stop()

This method is called when the webpage containing the applet is no longer visible or when a user navigates away from the page. This is where you'd put code to pause processes or save data that shouldn't run or be changed when the applet is not visible.

4. destroy()

This method is called only once, just before the applet is unloaded and its memory reclaimed by the JVM. This is the "death" of the applet, and any final cleanup (such as releasing resources) should happen here.

Here are some Java applet programs examples with output: 

This applet in Java displays a string telling you which methods have been called. The string gets updated each time a life cycle method is called. If you load this applet, navigate away, and then return, you'll see the messages reflecting the order in which the methods were called.

Applet Security

The applet in Java operates within a restricted environment known as a sandbox, limiting its interaction with the user's system for security reasons. This prevents malicious code from damaging a user's system or accessing sensitive data.

What is the Java Security Manager?

The Java Security Manager is a class included in the Java runtime environment that determines what operations an applet can perform. It serves as a gatekeeper, denying it access to certain system resources and capabilities unless explicitly granted.

How Applet Security Works

When an applet in Java attempts to perform a sensitive operation (like reading or writing a file), the Java runtime asks the Security Manager for permission. If the applet originated from the internet, the Security Manager usually denies the request unless a trusted entity signs the applet.

How to Sign Your Applet for Increased Security

Signing your applet involves creating a digital signature that guarantees the applet originates from a known and trusted source. This process involves acquiring a certificate from a Certificate Authority (CA) and signing your applet using tools provided with the JDK, such as keytool and jarsigner. 

After signing, a user's system will grant the applet more privileges, but users will be prompted to trust the signed applet before running it.

Applet Deployment

Deployment of Java applets typically involves embedding the compiled .class files within a web page using the <applet> HTML tag or the newer <object> tag. It's recommended to use the Java Network Launch Protocol (JNLP) for deploying applets as it provides additional features such as version control and offline access. 

The applet in Java should also be tested across various browsers and platforms to ensure broad compatibility.

Common Issues With Applet Deployment And How To Troubleshoot Them

1. Applet not loading: This may be due to issues with the JRE on the client's machine or errors in the applet's code.

Troubleshooting: Check your code and ensure the client has a suitable version of JRE installed.

2. Security exceptions: These occur when an applet performs operations outside its sandbox limitations.

Troubleshooting: Make sure your applet doesn't perform restricted operations. Revise the applet structure in Java to avoid operations that require special permissions or consider signing the applet.

Passing Parameters to Applet in Java

Passing parameters to an applet in Java is useful for providing configuration information or other input. It enables you to customize the behavior of an applet every time it's loaded without changing its source code.

To pass parameters to an applet, you use the <param> tag inside the <applet> tag in your HTML file. Each parameter has a name and a value.

Here's an example:

In your applet's Java code, you can retrieve the parameters using the getParameter method, which takes the parameter's name as an argument:

In this code, getParameter is called to retrieve the values of param1 and param2. The retrieved parameters are then used to display "Hello World" in the applet window. This technique demonstrates passing parameters to an applet in Java and how it enhances the applet's flexibility.

Features of Applets in Java over HTML

Applets offer many key features that extend beyond the capabilities of HTML:

Applets in Java:

1. Dynamic and interactive content.

2. Greater processing power with Java.

3. Superior graphics capabilities.

4. Can communicate over the network.

HTML:

1. Primarily for static web pages.

2. Limited interactivity.

3. Less processing power relies on JavaScript.

4. Limited graphics capabilities.

5. Network communication requires additional tech.

Conclusion

The applet in Java offers users a dynamic and interactive experience, enhancing traditional HTML's capabilities. Despite certain deployment challenges and security considerations, their ability to perform complex computations, support animations, and provide real-time responses makes them a potent tool for web development.

Nevertheless, due to the shift towards modern web technologies, weighing the pros and cons before opting for applets in a project is recommended.

FAQs

1. What are the alternatives to Applet in Java in modern web development?

Today, JavaScript, along with HTML5 and CSS3, is a popular choice for creating interactive web content. Other technologies include Flash and Silverlight, though these are becoming less common.

2. How do you handle persistent data with Java applets?

An applet, by default, can't write to the user's hard drive due to security restrictions. However, they can communicate with the server, so you can handle persistent data by storing it on the server side.

3. What is the role of double buffering in applet in Java?

Double buffering is a technique used in Java applets to prevent flickering during animations. It involves drawing and copying an off-screen image to the screen in one operation.

4. What are some limitations of the applet in Java? 

The applet in Java often shows several limitations. It may require Java Virtual Machine (JVM) installation, load slowly, and have limited functionality due to strict security. Moreover, it is not supported by many modern web browsers. 

Leave a Reply

Your email address will not be published. Required fields are marked *