Previous
Index

Next


Chapter 5 Applets and components

5.1) Applets

What is an applet?

Applets are Java programs embedded into web pages, allowing most of the functionality of a Java application but removing the need for separate downloading and installation. They user can interact with applets and pass responses back to process on the web server such as databases. They perform a similar role to flash pages except they come with some advantages (and disadvantages) by comparison. Flash has the advantage that it is especially suitable for creating animated images, and a user can do that with almost no knowledge of programming. As flash has developed, programming features have been added. Java has the advantage of being an industrial strength programming language that was designed from the ground up for software engineering. It also has more support for encryption and security than any alternative technology.

Alternatives to Applets

n the early days of the web many people thought that most web pages would involve Java applets, but much of the anticipated role has been taken up by Javascript (almost no relation to Java). Typical examples of early use of applets were dynamic menus or visual effects such as a rippling image of water on a lake. In an era where most internet connections involved a relatively slow dial up modem connection, the delay in downloading applets was generally not offset by a significant benefit. Users of web pages are not tolerant of delay and web designers found they could create an interface that was “good enough” with technologies like HTML and JavaScript. It's worth mentioning again that Java has almost nothing to do with JavaScript. At the time of writing the latest big hype is a technology called Ajax, which is effectively a very clever use of JavaScript. Ajax generally brings all the advantages and disadvantages of JavaScript and is not a substitute or alternative to applets.

There are still some tasks for which only a Java Applet will fully solve the problem. One of the benefits of applets is that once they are downloaded you do not have the performance benefit of server side applications where you are relying on a round trip to the server for each interaction, though of course JavaScript is frequently a more “lightweight” alternative for browser based interactivity.

You can see how complex an applet can be by running the applet embedded in the SwingSet2.htm file that gets installed with the JDK. With my installation of the JDK this was installed at

C:\Program Files\Java\jdk1.5.0\demo\jfc\SwingApplet\SwingApplet.html

Yours may be slightly different, but it will probably be found under the demo/jfc directory of your JDK installation. One of the significant benefits of Applets is that they have an extreemly good history of security, i.e. there have been very few, perhaps no examples of an applet corrupting information on the local file system. You may also read about a technology called Java Web Start which allows the automatic downloading and installation of Java programs which can offer some apparent performance benefits, because the program is not downloaded afresh with each access like applets. Java Web Start is a relatively new technology and outside the scope of this tutorial.

Swingset Screenshot

It is worth running this demonstration application as it shows off just how sophisticated an interface can be built with the Java Swing classes. It shows off slider controls, tree controls, tabbed forms, graphical buttons and just about everything you would expect in a modern interface.

Browser wars

The history of Applets was caught up in the “Browser Wars” between Microsoft and Netscape and the political and business battles between Microsoft and Sun Microsystems. One of the problems of the early days was that of incompatibility. When developing an applet you had to test it against different web browsers and Java implementations. If you recall that one of the great promises of Java was “write once run anywhere” this was rather a severe blow. Today these issues are mainly history as the standard target for Java applets to day is the Sun Java Runtime, a way of allowing just about any browser to be enabled with exactly the same Java Runtime Environment (JRE).

When it appeared that applets might take over the web Microsoft introduced what was considered a competing technology in the form of ActiveX controls. The big criticism of activeX at the time was that it was not secure and it was possible to create a malicious activeX control that could access the users local hard disk. Also activeX controls were only available for the windows platform.

Applets are particularly suitable for any task that requires a fully featured industrial strength programming language. An example of this is anything connected with security. Javascript is inherently not suited to security based tasks because it is so easy to view the source code. Java Applets by contrast arrived in the form of binary .class files and the JRE has a built in security system that makes it difficult for a rogue applet to cause problems on a client computer. It is arguable that the Browser Wars are back since the huge success of the Mozilla Firefox browser. This success has come about even since the first draft of this text. With FireFox taking around 10% of the browser market, the increased desktop market share of Linux, and huge take up of broadband internet access, Applets are going to continue to be an important technology.

Applets and performance

Historically applets have been the target of accusations of poor performance, of being slow. Be very careful whenever you hear any technology described as slow, exactly what part is slow. Applets are not slow, the generally run just as quickly as any other program you can thing of. However they can be slow to access, i.e. pull of the network, and if the JVM is not running there can be a pause as java starts up. With the increasing penetration of broadband the network access time is much less of an issue and with the increasing performance of CPU chips and the JVM the start up time is less of an issue.

Applications vs Applets

Most of the ideas you have learnt about applications can be applied to applets. One of the key benefits of applets over applications is that they do not have to be installed. If you consider the work that is required to install conventional applications in terms of selecting components and the install directories, you may appreciate the reduced “overhead” of applets.

One of the main areas of difference is security, particularly in accessing local resources. The main restrictions are as follows.

Applets cannot read or write the the file system of the browser user. This means they cannot delete files or test to see what programs you have installed. In contrast to this, some versions of JavaScript in the leading web browsers were able to access the local file system, leading to the possibility of rogue code.

Applets cannot communicate with any network server other than the one where the applet was originally loaded from. This prevents an applet from attacking another system from the readers system.

Applets cannot run any program on the reader system, e.g. You cannot load the local copy of notepad or an MS Office program when running on the MS Windows platform.

Applets cannot load local programs such as DLLS (dynamic link libraries).

Applets cannot make a network connection to any host apart from the one that it was loaded from. Thus for example you cannot create an Applet for loading the HTML content from multiple web sites.

Another consideration is that applets cannot start up new windows in the same way that applications do. If an Applet were to open a new Window, how could you be sure it was on top of the other windows and not hidden behind?

These restrictions are known as the Java sandbox. It is possible to configure applets with a finer grade of security using digital signatures and encryption. With signed applets you are asked if you want to allow the applet greater access to your system than the default and you have to decide if you trust the developers not to violate your system.

Hello World

Putting an applet in a web page requires the use of the <applet> tag. To use this tag you need to know how to use the parameters that indicate where the Java class file is and any other details that it will require when it starts up within the browser. Applets start in a different way to applications. Applications start with the “magically named” method main which is invoked when the application is started from the command line. Applets by contrast are controlled by the action of loading the web page that they were embedded in and have a different sequence of methods invoked at start up time.

HelloApplet

In the same way that the first application was HelloWorld, here is an example of a basic HelloApplet.

public class HelloApplet extends javax.swing.JApplet{
        public void paint(java.awt.Graphics g){
                g.drawString("Hello",30,10);
        }
}

Note that the HelloApplet class extends the javax.swing.JApplet class, which provides the graphical capabilities in a similar way that a command line graphical program might extend the javax.swing.JFrame class. An applet such as this is compiled in the same way as an application, i.e.

javac HelloApplet.java

and the resultant output will be a file called

HelloApplet.class

In order to view this applet you need to create a basic HTML file that embeds the applet in the web page.

It can be as little as the single lines

<applet code=HelloApplet.class width=200 height=100> </applet>

Note how the reference to the applet includes the .class extension, unlike when you run an application where you do not include a reference to the class extension. Note how there is nothing between each parameter to the class, i.e. There is no comma between width=200 and height=100.

There are two ways of view applet, either using the appletviewer tool that comes with the JDK or by opening the html file using a Java enabled browser. One of the disadvantages of appletviewer is that it does not implement all the security precautions of the applet plugin. I have wasted a great deal of time testing a program with the appletviewer only to find it did not work in a browser because I was using methods that accessed files, so don't rely entirely on the applet viewer. However for basic testing and learning the appletviewer is quick and convenient and available from the command line. So to test HelloApplet you can type the following command line

appletviewer helloapplet.htm

The parameters to the drawString methods are the x,y co-ordinates, and in the example given it positions the output string at the top of the applet window. If you were writing the equivalent application you could pass the x,y co-ordinates from the command line and extract them from the String array that is the parameter to the main method. However there is no command line with a page embedded within a web browser. You can pass the equivalent of command line parameters to an applet by embedding them into the html and capturing them when the applet starts.

Passing parameters to an applet requires additional <param ....> tags between the starting <applet> tag and closing </applet> tag. For example, if you wanted to pass the x,y co-ordinates to the helloapplet you could have parameters passed with the following code.

<applet code=HelloApplet.class width=100 height=100>

<param name="greeting" value="bonjour">

</applet>

Note that the name of the parameter can be just about anything that makes sense to you and the value will be passed as string to the applet. Examples of parameters being passed to applets are where an applet acts as a “news ticker” and the parameter is passed as part of the html. Of course the html can be generated from a server side interaction.

Applets and Jars

Because applet class files are loaded using the standard HTTP protocol, each request has a significant performance overhead. Thus accessing each .class file involves a negotiation between the browser and the server. To reduce this overhead the .class files can be wrapped up in a single Jar file, and as a result only one HTTP protocol setup and download cycle is required, resulting in a potential significant performance benefit.

Applet Lifecycle

If you take a look at the earlier sample applets you will notice that unlike applications they have no main method. An applet life cycle is controlled by the init and start methods. The init method is executed when the applet is first loaded into memory, and the start method runs each time the browser visits the page containing the applet. In the HelloApplet example given neither of these methods are defined and so the versions that are called are the default ones supplied by the JApplet class. The default start method has a call to the paint method, which is why those sample applets worked. Note that you generally never call the init or start methods yourself, they are called by the browser at at the appropriate times.

The applet console.

Although applets do not have the standard command line console, you can see the non GUI output from an applet via the applet console. In Microsoft IE you can access this from the Tools/Sun Java Console or from Netscape/Mozilla it is visible from Tools/Web Development/Java Console. This can be useful if you load an applet from a web site and it does not appear to work correctly. Typically this can be a failure to locate classes needed in an applet and in my own experience it allowed me to track down an error where I was using classes that the Java Runtime thought was trying to access the local file system.

Components

In this context I am using the word component to refer to the discreet “things” that appear on a gui interface. Thus the include things that users can click, scroll, type into etc. Different languages and operating systems have used different names, thus in the world of Microsoft Windows the term control is used and in the world of Linux they are referred to as “widgets”. There are three possible types of widgets supported by Java, they are AWT, Swing and SWT. AWT was the widget set supported by early Java, SWT is a system created mainly support the Eclipse editing tool and Swing is used for about 99% of all Java GUI programming. You probably don't need to know anything about SWT or AWT apart from the fact that they exist and are rarely used.

Every Swing control is a subclass of javax.swing.JComponent and so they inherit several basic methods and fields of that class. JComponents can be serialized, i.e. The current state of a running JComponent can be written out to disk or over a network, and can be read in again. I like to think of this as instant freeze drying of the state of a component except when the component is unfrozen it is “as good as new” with no loss of flavour or texture.

The Swing libraries are a huge topic and I can only hope to give you a flavour of what is possible. There are some general principles of programming the Swing libraries and once you have worked with a few of the components, learning others should not be difficult.

The JComponent class

Jcomponent is abstract, i.e. It cannot be instantiated itself but can be a parent of another class. In reality, much of the time you will be creating instances of classes for which Jcomponent is a great grandparent. Some of the generic characteristics provided by Jcomponent are


Other Sources

The Sun Java Tutorial on applets
http://java.sun.com/docs/books/tutorial/deployment/applet/index.html

Java Web Start vs Applets
http://mindprod.com/jgloss/javawebstart.html




Previous
Index

Next