16. Java Applets
Java Applets
The chief function of a Web browser is to format content (of the page being viewed). Scripting languages such as Javascript allow considerable functionality for both client- and server-side programming, but these languages do not have the abilities and power of a fully-fledged high-level OOP language. Java Applets allow almost the full functionality of the Java language to become available in the pages displayed by a Web browser.
Applets are Java programs that run in your Web browser. The code for the Applet is stored on a server and then downloaded into the browser. This has the advantage that any computer that has Internet access can run a Java Applet, but also has the disadvantage that you have to wait for the code to download before you can run the Applet. This is no problem if you have a high-speed connection, but over a phone-line this can take quite some time for a complex program. Consequently, highly complex Applets are not common on the Web, but they are easily implemented in company intranets and other reasonably fast distributed systems. Such programs can then be written and stored in one place and made easily available to everybody that needs to use them. Maintenance then become easy because any changes only need to be made in one place.
Browsers run on many different platforms - Windows, Mac, Linux, etc. so Applets must be able to run on multiple platforms. The platform independence of Java makes it perfect for developing Applets - any machine that has a copy of the Java VM can happily run any Java Applet. Java Applets have the added advantage that they are safe to run, because they are implemented in a so-called sandbox and have no access to your computer's system unless you physically give the Applet permission to access the system or some part thereof.
To implement an Applet in a browser, you need to use the special <APPLET> tag. In it's simplest form, this tag provides the name and location of the Java class file for the Applet, and a size for the Applet to assume in the page:
<APPLET code="myApplet.class" width=200 height=120></APPLET>
Applets in Java are the only applications that are not required to have a main() method, because the browser and not the Applet is responsible for loading and running the Applet. Applets usually call the paint(Graphics g) method of the java.awt package. This package includes the Graphics class, and the paint(Graphics g) method takes a Graphics object as argument. The paint(Graphics g) method fills in the surface of the Applet whenever required to do so, i.e. when the Applet is loaded for the first time and for every time that the page is refreshed in the browser. We'll explore this more fully over the next few pages.






