Java Applet: A Comprehensive Guide

Author

Reads 11K

A woman studying Java programming on a sofa with a MacBook and other computer books nearby.
Credit: pexels.com, A woman studying Java programming on a sofa with a MacBook and other computer books nearby.

Java applets are small programs that run on the web, allowing users to interact with dynamic content on websites. They were introduced in the mid-1990s and quickly gained popularity.

Java applets are executed by the Java Runtime Environment (JRE), which is a software package that provides the necessary libraries and tools for running Java programs. The JRE is installed on the user's computer.

A Java applet consists of a class file, which contains the applet's code, and a manifest file, which provides metadata about the applet. This metadata includes the applet's version, author, and other information.

Java applets can be used to create interactive web pages, such as games, animations, and calculators.

What is a Java Applet?

Java applets are interactive features that can be embedded in web applications to provide a richer user experience. They can capture mouse input and have controls like buttons or check boxes.

Applets are well-suited for demonstration, visualization, and teaching, and there are online collections for studying various subjects, from physics to heart physiology.

Credit: youtube.com, What was a Java applet?

An applet can also be a text area only, providing a cross-platform command-line interface to some remote system. This makes it a useful tool for certain applications.

Applets can leave their dedicated area and run as a separate window if needed, but they have very little control over web page content outside their area.

Technical Details

Java applets were executed in a sandbox by most browsers, preventing them from accessing local data like the file system.

The code of the applet was downloaded from a web server and then either embedded into a web page or opened in a new window showing the applet's user interface.

Java system libraries and runtimes are backwards-compatible, allowing code to run on both current and future versions of the Java virtual machine.

Applets were initially slow-loading due to the need to download each class individually, but the introduction of .jar files improved performance by allowing applets to be delivered as a single file.

Life Cycle

House with colorful illustrations on walls showing coffee life circle and production process
Credit: pexels.com, House with colorful illustrations on walls showing coffee life circle and production process

The life cycle of an applet in Java is a crucial concept to grasp when building interactive web applications. It's a series of methods that are called at specific times during the applet's execution.

The init method is called after the param tags inside the applet tag have been processed. This is where you can perform any necessary initialization for your applet.

The start method is automatically called after the browser calls the init method. It's also called whenever the user returns to the page containing the applet after having gone off to other pages.

There are four key methods in the Applet class that give you the framework on which you build any serious applet:

  • init
  • start
  • stop
  • destroy

The stop method is automatically called when the user moves off the page on which the applet sits. It can be called repeatedly in the same applet.

The destroy method is only called when the browser shuts down normally. This is a good reminder to clean up any resources your applet is using.

The paint method is invoked immediately after the start method, and also any time the applet needs to repaint itself in the browser.

Technical Information

Credit: youtube.com, Technical Information Program

Java applets were executed in a sandbox by most browsers, preventing them from accessing local data like the file system. This was a key security feature that helped keep users' computers safe.

The code of the applet was downloaded from a web server, after which the browser either embedded the applet into a web page or opened a new window showing the applet's user interface. This process was often slow, especially when applets were downloaded class by class.

However, with the introduction of .jar files, applets could be delivered as a single file with a size similar to an image file (hundreds of kilobytes to several megabytes). This made applets much faster to load.

Java system libraries and runtimes are backwards-compatible, allowing one to write code that runs both on current and on future versions of the Java virtual machine. This is a huge advantage for developers, as it means their code won't become obsolete anytime soon.

Here are some related terms that are worth noting:

  • Java (programming language)
  • Java platform
  • Web 1.0

Advantages and Disadvantages

Credit: youtube.com, What Is A Java Applet? - History Icons Channel

Java applets had their fair share of advantages and disadvantages.

One of the biggest advantages was that they were simple to make cross-platform, working on FreeBSD, Linux, Microsoft Windows, and macOS without much hassle.

Java applets also moved work from the server to the client, making web solutions more scalable with the number of users/clients. This is because the server didn't need to support all prior versions of software, unlike standalone programs.

Here are some of the key advantages of Java applets:

  • Simple cross-platform compatibility
  • Scalable web solutions
  • Work moved from server to client
  • No need to support legacy versions
  • Faster performance
  • Improved with use
  • Secure, with access to local machine only with user agreement

However, there were also some significant disadvantages to using Java applets. One of the main issues was that they required a Java Runtime Environment (JRE) and a plug-in for the web browser, which could be a problem for some users.

Advantages

Java applets were a game-changer in the early 2000s, offering several advantages that made them a popular choice for web development.

One of the biggest advantages of Java applets was their ability to work across multiple platforms. They could run on FreeBSD, Linux, Microsoft Windows, and macOS, making them a great option for developers who wanted to reach a wide audience.

A black woman sits on a sofa by a window, reading a Java programming book, reflecting on its content.
Credit: pexels.com, A black woman sits on a sofa by a window, reading a Java programming book, reflecting on its content.

Applets were also easy to develop and debug. Developers could create a main routine and call init() and start() on the applet, allowing them to test and refine their code without needing to worry about security restrictions.

A Java applet could have any or all of the following advantages:

  • It was simple to make it work on FreeBSD, Linux, Microsoft Windows and macOS – that is, to make it cross-platform.
  • The same applet would work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only.
  • Most web browsers cached applets so they were quick to load when returning to a web page.
  • Applets improved with use: after a first applet is run, the JVM was already running and subsequent applets started quickly.
  • It moved work from the server to the client, making a web solution more scalable with the number of users/clients.
  • If a standalone program talks to a web server, that server normally needs to support all prior versions for users who have not kept their client software updated.
  • Applet naturally supported changing user state, such as figure positions on the chessboard.
  • Developers could develop and debug an applet directly simply by creating a main routine.
  • An untrusted applet had no access to the local machine and can only access the server it came from.
  • Java applets were fast, with similar performance to natively installed software.

Disadvantages

Java applets had several disadvantages compared to other client-side web technologies, making them less desirable for many users. One major issue was the requirement for a Java Runtime Environment (JRE), a complex and heavy-weight software package that many users didn't want to install.

This meant that users had to wait for the large JRE download to complete before they could even start using an applet. Mobile browsers on iOS or Android devices never supported Java applets at all.

The lack of standardization for making applet content available to screen readers also harmed the accessibility of web sites to users with special needs. This was a significant disadvantage, especially for users who relied on screen readers to navigate the web.

Close-up of a computer screen displaying colorful programming code with depth of field.
Credit: pexels.com, Close-up of a computer screen displaying colorful programming code with depth of field.

Security restrictions made it difficult or even impossible for some untrusted applets to achieve their desired goals. To grant access to the local filesystem or system clipboard, or to network sources other than the one that served the applet to the browser, users had to edit the java.policy file in the JAVA JRE installation.

The distinction between untrusted and trusted applets didn't help much with security, as most users didn't care about the difference. This led to the ability to run untrusted applets being removed entirely to fix the issue.

Security and Certificates

Java applets have a complex security model, with two main types: signed and unsigned. Signed applets contain a signature that a browser verifies through a remotely running certificate authority server.

Unsigned applets were considered "draconian" due to their limitations, including no access to the local filesystem and web access limited to the applet download site.

Starting with Java SE 7 Update 21, applets and Web-Start Apps are encouraged to be signed with a trusted certificate, and warning messages appear when running unsigned applets. Unsigned applets were blocked by default starting with Java 7 Update 51.

A fresh viewpoint: Dial up Networking

Credit: youtube.com, Signing Applets Using RSA Certificates

Self-signed applets, signed by the developer themselves, may pose a security risk and are usually only used during development. Java plugins provide a warning when requesting authorization for a self-signed applet.

As of 2014, self-signed and unsigned applets are no longer accepted by the commonly available Java plugins or Java Web Start.

Creating and Running

You can run a Java applet by using the appletviewer command with your Java source code file. If your source file includes a comment with the APPLET tag, you can simply run the applet by starting the applet viewer with your Java source code file.

To run an applet, you can use the appletviewer command followed by the name of your Java source code file. For example, if your file is named HelloWorld, you would run the command appletviewer HelloWorld.

Here are some examples of what you can do with a Java applet:

  • Displaying dynamic web pages of a web application.
  • Playing sound files.
  • Displaying documents
  • Playing animations

Source File

When you include a comment with the APPLET tag at the head of your Java source code file, you can run your compiled applet by starting the applet viewer with your Java source code file.

A programmer sits thoughtfully at his desk with computer screens and office setups, reflecting modern workplace dynamics.
Credit: pexels.com, A programmer sits thoughtfully at his desk with computer screens and office setups, reflecting modern workplace dynamics.

This approach is particularly useful for documenting your code with a prototype of the necessary HTML statements. For example, the HelloWorld source file looks like this:

If you use this method, you can compile the HelloWorld.java file and then simply run the below command to run the applet:

appletviewer HelloWorld

You can use the applet viewer to display dynamic web pages, play sound files, display documents, and play animations.

Here are some of the key features of the applet viewer:

  • Displaying dynamic web pages of a web application.
  • Playing sound files.
  • Displaying documents
  • Playing animations

Creating and Running

To create an applet, you need to start with a Java class that extends the Applet class. The HelloWorld applet is a great example of this, where the class HelloWorld extends the Applet class.

The HelloWorld applet begins with two import statements, one for the Applet class and one for the Graphics class. These classes are necessary for creating an AWT-based applet.

To run an applet, you can use either an applet viewer or a Java-compatible web browser. The applet viewer executes your applet in a window, which is generally the fastest and easiest way to test your applet.

Futuristic workspace featuring a glowing computer screen with coding displayed, ideal for technology and programming concepts.
Credit: pexels.com, Futuristic workspace featuring a glowing computer screen with coding displayed, ideal for technology and programming concepts.

You can also run an applet by including a comment at the head of your Java source code file that contains the APPLET tag, and then running the applet viewer with your Java source code file.

Here are the two standard ways to run an applet:

  • Using an applet viewer, such as the standard tool, applet-viewer.
  • Executing the applet within a Java-compatible web browser.

The width and height statements in the HTML file specify the dimensions of the display area used by the applet.

If you want to run an applet as an application, you can do so by adding a main method to the applet class. However, this will not work if the applet is run as an applet, as the main method is not relevant in that case.

Here are some key differences between running an applet and running an application:

  • Applets do not have a main method.
  • Applets are subject to security restrictions to prevent viruses or malicious code.
  • Applets are displayed inside the browser, whereas applications have their own windows.

Restrictions and Limitations

Java applets are restricted in several ways due to security concerns.

An applet cannot load libraries or define native methods, which severely limits its capabilities.

Credit: youtube.com, What Is A Java Applet? - SecurityFirstCorp.com

Applets are also restricted from reading or writing files on the execution host, which means they can't access or modify local files.

Certain system properties are also off-limits to applets, which can make it difficult to access specific information.

Applets can only make network connections to the host they came from, which can be a limitation for certain types of applications.

Applets are also unable to start any program on the host that's executing it, which means they can't launch other applications or processes.

Event Handling and Graphics

Event Handling and Graphics are two crucial aspects of Java applets. Applets can handle events like mouse clicks and key presses by overriding methods inherited from the Container class.

The Container class provides methods like processKeyEvent and processMouseEvent for handling specific events, and a catch-all method called processEvent. To react to an event, an applet must override the appropriate method.

Applets use the java.awt package for GUI components and event-handling mechanisms. Key packages for Java applets include java.applet.Applet, java.awt.Graphics, and java.awt.

Here are some key packages for Java applets:

  • java.applet.Applet: Base class for applets.
  • java.awt.Graphics: Used for drawing on the applet screen.
  • java.awt: Provides GUI components and event-handling mechanisms.

Key Packages

Credit: youtube.com, Events - Interactive 3D Graphics

Key Packages are essential for building Java Applets.

The base class for applets is java.applet.Applet. This class provides the foundation for creating applets.

The java.awt package is a crucial package for GUI components and event-handling mechanisms.

To draw on the applet screen, you'll need to use the java.awt.Graphics class.

Here are the key packages you'll need to get started:

  • java.applet.Applet: Base class for applets.
  • java.awt.Graphics: Used for drawing on the applet screen.
  • java.awt: Provides GUI components and event-handling mechanisms.

Event Handling

Applets can react to events by overriding specific event-handling methods, such as processKeyEvent and processMouseEvent, which are inherited from the Container class.

The Container class defines a catch-all method called processEvent that handles events not covered by the event-specific methods.

To handle events, an applet must override the appropriate event-specific method.

Applets can display messages in response to events, such as displaying "mouse clicked" after a mouse click event.

The applet's behavior can be customized by overriding the event-handling methods to suit the applet's specific needs.

Displaying Images

Displaying images within an applet is a straightforward process. You can display images in various formats like GIF, JPEG, BMP, and others using the drawImage() method from the java.awt.Graphics class.

Monochrome image of a DSLR screen displaying a portrait, emphasizing photography.
Credit: pexels.com, Monochrome image of a DSLR screen displaying a portrait, emphasizing photography.

To display an image, you'll need to use the drawImage() method, which is found in the java.awt.Graphics class. This method allows you to show images within your applet.

The drawImage() method is a powerful tool for adding visual interest to your applet. It can display images in various formats, including GIF, JPEG, and BMP.

Playing Audio

Playing audio in an applet can be done using the AudioClip interface, which has three methods: play(), loop(), and stop(). To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.

The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded until an attempt is made to play the audio clip.

Here are the methods of the AudioClip interface:

  • play() − Plays the audio clip one time, from the beginning.
  • loop() − Causes the audio clip to replay continually.
  • stop() − Stops playing the audio clip.

To test the audio playback, you can use the test.wav file on your PC.

Subroutine

A subroutine is a segment of code that performs a specific task, but unlike an applet, it's not a complete web component. It's essentially a reusable piece of code that can be called from multiple places within a program.

Credit: youtube.com, Event Handling (Computer 10)

Subroutines are often contrasted with applets, which provide more functionality and performance beyond the default capabilities of their container. A key difference is that applets are written in a compiled language, whereas subroutines are not necessarily written in a different language.

In fact, applets are restricted by their container, which limits their capabilities. Subroutines, on the other hand, can be implemented in various ways, but they're not a standalone web component like an applet can be.

Here's a comparison between applets and subroutines:

Running and Conversion

Running a Java applet is quite straightforward, but converting an existing Java application to an applet requires some specific steps.

To convert an application to an applet, you'll need to make an HTML page with the appropriate tag to load the applet code. This is where you'll specify the applet's class and other necessary details.

You'll also need to supply a subclass of the JApplet class, which must be public in order for the applet to be loaded. This class will serve as the foundation for your applet.

Credit: youtube.com, Java 2D Game Engine Development - Converting to an Applet

Eliminating the main method in your application is another crucial step in the conversion process. You won't need to construct a frame window for the applet, as it will be displayed inside the browser.

To get your applet up and running, you'll need to move any initialization code from the frame window constructor to the init method of the applet. This is where the browser will instantiate the applet and call the init method.

Here are the key steps to convert an application to an applet:

  • Make an HTML page with the appropriate tag to load the applet code.
  • Supply a subclass of the JApplet class.
  • Eliminate the main method in the application.
  • Move any initialization code to the init method of the applet.
  • Remove the call to setSize.
  • Remove the call to setDefaultCloseOperation.
  • Eliminate the call to setTitle.
  • Don't call setVisible(true).

Frequently Asked Questions

Do Java applets still exist?

Java applets are no longer supported, having been deprecated in Java 9 in 2017. However, legacy applets may still exist in older systems and applications.

Thomas Goodwin

Lead Writer

Thomas Goodwin is a seasoned writer with a passion for exploring the intersection of technology and business. With a keen eye for detail and a knack for simplifying complex concepts, he has established himself as a trusted voice in the tech industry. Thomas's writing portfolio spans a range of topics, including Azure Virtual Desktop and Cloud Computing Costs.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.