Java Applets And GUI Programming

What Are Applets?

Java applets are Java applications designed to run inside of a Web browser. This approach gives you the flexibility of a full graphical application (vs. HTML forms) without many of the problems of configuration management usually associated with graphical applications, such as installation, version upgrades, and accessibility. Java applets run inside of a Web browser, so just pointing your Web browser to the right page will load the most recent version of the applet if necessary. Since applets run inside of a Web browser they can be easily accessible from any computer on the Internet equipped with a Web browser. Applets also provide a security model that prevents them from accessing sensitive system resources. For example, by default, applets cannot write to files on the hard drive (this, among other things, can be modified using a policy file loaded on the user's computer) and they can never connect to a machine on the Internet other than the one from which the applet was downloaded in the first place.

Problems With Applets

Microsoft's Internet Explorer, which is the most widely used Web browser, only supports Java 1.1, a very old version of Java. So the applets you can run in IE in this manner are rather limited. If you want to use the full power of JDK 1.2 and higher in an applet running inside of Internet Explorer, you must load the applet inside of the Java Plugin (an ActiveX control provided by Sun for IE). If the user's PC does not have the right version of Java installed, the Java Plugin will automatically download it from the Internet and install it. Since newer  JDKs are quite large, this may not be a viable option for general-purpose use. However, such applications are not uncommon in business Intranet environments where the network connectivity is fast or where allo PCs have the right version of Java pre-installed.

AWT vs. Swing

Java supports two sets of APIs for graphics programing. AWT is the "old way" and is mostly considered obsolete, and Swing is the "new way." This can be a bit confusing because many classes in the java.awt package are still used as a base for Swing components. But the overall approach is indeed quite different. The primary differences between AWT and Swing are as follows:
We won't discuss these differences in detail. Unless you are writing applets that you wish to run directly in Internet Explorer using JDK 1.1, you probably don't need to worry about AWT. You shoul not mix swing and awt components in one application. If you are interested in doing graphical programming in Java, I suggest you learn Swing... If you are doing plugin programming for Eclipse, you have to use a custom graphical API written for eclipse. Also, Java for mobile phones and handhelds tends to have its own graphical APIs depending on the particular technology you are working with.

Loading Applets In A Web Browser

This is a bit tricky. You can either use the <APPLET> tag in an HTML file (see below). Or you can use <OBJECT> tag code for the browser you're in (generally you should support at least IE and Netscpe/Mozilla -- although if you know all of your users are using IE, you can just provide support for IE). Using the <OBJECT> or <EMBED> tags lets you specify the version of the Java virtual machine you wish the Plugin to use (and load if necessary).
    <APPLET CODE=applet/AppletDemo.class WIDTH=250 HEIGHT=250></APPLET>

A Simple Applet

package applets;

import java.applet.Applet; //or try javax.swing.JApplet
import java.awt.*;
import java.awt.event.*;

public class AppletDemo extends Applet /* or try JApplet */ {

    StringBuffer buffer;

    public void init() {
    buffer = new StringBuffer();
    addItem("initializing... ");
    this.addMouseListener(new MouseEventDemo());
    addItem("intialized!");
    }

    public void start() {
        addItem("starting... ");
    }

    public void stop() {
        addItem("stopping... ");
    }

    public void destroy() {
        addItem("preparing for unloading...");
    }

    void addItem(String newWord) {
        System.out.println(newWord);
        buffer.append(newWord);
        repaint();
    }

    public void paint(Graphics g) {
        //Set color to red
        g.setColor(Color.red);

        //Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0, size().width - 1, size().height - 1);

        //Draw the current string inside the rectangle.
        g.drawString(buffer.toString(), 5, 15);
    }
   
    //this is an inner class!
    class MouseEventDemo implements MouseListener {     
        public void mousePressed(MouseEvent e) {
           log("Mouse pressed; # of clicks: "
                        + e.getClickCount(), e);
        }

        public void mouseReleased(MouseEvent e) {
           log("Mouse released; # of clicks: "
                        + e.getClickCount(), e);
        }

        public void mouseEntered(MouseEvent e) {
           log("Mouse entered", e);
        }

        public void mouseExited(MouseEvent e) {
           log("Mouse exited", e);
        }

        public void mouseClicked(MouseEvent e) {
           log("Mouse clicked (# of clicks: "
                        + e.getClickCount() + ")", e);
        }

        void log(String eventDescription, MouseEvent e) {
            String message = eventDescription + " detected on "
                            + e.getComponent().getClass().getName()
                            + ".";
            addItem(message);
        }
    }
}

A Simple Swing Applet

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AppletDemo extends JApplet {

JLabel label= new JLabel("Enter Your Name");
JTextField field= new JTextField();
JButton button=new JButton("Click Me");

public void init() {
field.setPreferredSize(new Dimension(100, 30));

Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

contentPane.add(label);
contentPane.add(field);
contentPane.add(button);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = field.getText();;
JOptionPane.showMessageDialog(AppletDemo.this, "You entered: " + message);
}
});
}
}