13: GUI Programming

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

13.1: Laying Out Components

Objectives

At the end of the lesson the student will be able to:

  • Describe the purpose of a layout manager
  • Use the Flow layout Manager
  • Use the Border layout Manager
  • Describe how to organize layout code

13.1.1: About Layout Managers

  • When you add multiple components to a GUI, your program has to set the size and position of each component.
  • You use a layout manager to provide this functionality
  • Each Container object has a default layout manager
  • For instance, a JPanel uses a FlowLayout manager
  • On the other hand, content panes like those used in JFrame use a BorderLayout manager
  • Normally, you only need to think about layout managers when:
    • You add components to a container
    • You do not like the default layout manager
  • To add a new layout manager, you use the setLayout() method of the container
  • We will discuss two commonly used layout managers in the next few sections

Method of the Container Class Used to Change Layout Managers

Method Description
setLayout(LayoutManagerObj) Sets the layout manager for this container.

13.1.2: Using the FlowLayout Manager

  • The FlowLayout manager is the default for a JPanel
  • It adds components to the top of a container moving from left to right
  • When a container runs out of horizontal space, it starts adding components to a new row
  • You can adjust the alignment of the components on a row using the alignment fields of the FlowLayout class:
    • FlowLayout.CENTER
    • FlowLayout.LEFT
    • FlowLayout.RIGHT

Commonly Used Constructors of the FlowLayout Class

Constructor Description
FlowLayout() Constructs a new FlowLayout with a centered alignment.
FlowLayout(intAlign) Constructs a new FlowLayout with the specified alignment.

For Example

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

public class FlowLayoutApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public FlowLayoutApp() {
        super("Flow Layout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("Button One");
        button2 = new JButton("Button Two");
        button3 = new JButton("Button with a long name");
        button4 = new JButton("Button Four");
        button5 = new JButton("5");

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT));
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);

        Container contentPane = getContentPane();
        contentPane.add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new FlowLayoutApp();
    }
}

More Information

13.1.3: Using the BorderLayout Manager

  • You can align buttons left or right with a FlowLayout manager
  • However, you cannot place buttons at the bottom of the container
  • To do that, you use the BorderLayout manager
  • With a BorderLayout manager, you can place components in 5 separate regions
  • To create a new BorderLayout, you typically call its no-arg constructor:
  • BorderLayout bl = new BorderLayout()
    
  • To add the BorderLayout to a container you use the setLayout() method
  • panel.setLayout(new BorderLayout());
    
  • The default layout manager of a content pane is BorderLayout
  • To add a component to a container using a BorderLayout, you specify:
  • add(ComponentObj, regionField);
  • If you do not specify the region, the component is added to the center region

Commonly Used Constructors of the BorderLayout Class

Constructor Description
BorderLayout() Constructs a new BorderLayout.

For Example

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

public class BorderLayoutApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public BorderLayoutApp() {
        super("BorderLayout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("North");
        button2 = new JButton("South");
        button3 = new JButton("East");
        button4 = new JButton("West");
        button5 = new JButton("Center");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(button1, BorderLayout.NORTH);
        panel.add(button2, BorderLayout.SOUTH);
        panel.add(button3, BorderLayout.EAST);
        panel.add(button4, BorderLayout.WEST);
        panel.add(button5, BorderLayout.CENTER);

        Container contentPane = getContentPane();
        contentPane.add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new BorderLayoutApp();
    }
}

More Information

13.1.4: Other Layout Managers

Java provides other layout managers you can research and use including:

  • BoxLayout: positions components in a single row or column
  • CardLayout: lets you create an area that can contain different components at different times
  • GridBagLayout: places components in a grid and allows some components to span more than one cell
  • GridLayout: displays components with equal size in a row-column layout like a spreadsheet
  • SpringLayout: allows you to specify precise relationships between the edges of components

More Information

13.1.5: Absolute Positioning

  • It is possible to do without a layout manager and use absolute positioning
  • However, you should use a layout manager if at all possible
  • Not using a layout manager restricts the user interface
  • To show the components optimally, you often need to make the frame not resizeable
  • A fixed-size frame can interfere with other applications the user is running
  • To get a feel for these limitations, run the following example

Example of Absolute Positioning

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

public class AbsoluteApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 170;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public AbsoluteApp() {
        super("Absolute Positioning Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("Button One");
        button2 = new JButton("Button Two");
        button3 = new JButton("Button with a long name");
        button4 = new JButton("Button Four");
        button5 = new JButton("5");

        button1.setBounds(10, 10, 100, 50);
        button2.setBounds(120, 10, 100, 50);
        button3.setBounds(230, 10, 150, 50);
        button4.setBounds(10, 70, 100, 50);
        button5.setBounds(120, 70, 50, 50);

        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);

        Container contentPane = getContentPane();
        contentPane.add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new AbsoluteApp();
    }
}
  • To remove the layout manager, you set the layout to null
  • panel.setLayout(null);
    
  • Now you need to set the position and size of each component individually
  • button1.setBounds(10, 10, 100, 50);
    

More Information

13.1.6: Summary

  • When you add multiple components to a GUI, your program has to set the size and position of each component
  • You use a layout manager to provide this functionality
  • Normally, you only need to think about layout managers when:
    • You add components to a container
    • You do not like the default layout manager
  • To set a new layout for a container, you use the setLayout() method
  • To set a new FlowLayout for a panel, you code something like:
  • panel.setLayout(new FlowLayout(FlowLayout.LEFT));
    
  • To set a new BorderLayout for a panel, you code something like:
  • panel.setLayout(new BorderLayout());
    
  • To add a component to a container using a BorderLayout, you code something like:
  • panel.add(button1, BorderLayout.NORTH);
    
  • If you do not specify the region, the component is added to the center region
  • Java has other layout managers you can use
  • Also, you can remove the layout manager and set all the component positions and sizes individually
  • However, you produce more professional and user friendly applications by using a layout manager

Exercise 13.1

  1. Label this exercise: Exercise 13.1
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise12.txt.

Specifications

  1. Compile and run the BorderLayoutExer.java code shown below.
  2. Revise the code so that the buttons are displayed in a row like this:
  3. Submit your updated code along with these exercises
import java.awt.*;
import javax.swing.*;

public class BorderLayoutExer extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 450, HEIGHT = 150;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public BorderLayoutExer() {
        super("BorderLayout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("Button 1");
        button2 = new JButton("Button 2");
        button3 = new JButton("Button 3");
        button4 = new JButton("Button 4");
        button5 = new JButton("Button 5");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(button1, BorderLayout.NORTH);
        panel.add(button2, BorderLayout.SOUTH);
        panel.add(button3, BorderLayout.EAST);
        panel.add(button4, BorderLayout.WEST);
        panel.add(button5, BorderLayout.CENTER);

        Container contentPane = getContentPane();
        contentPane.add(panel, BorderLayout.CENTER);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new BorderLayoutExer();
    }
}

13.2: Using Labels and Text Fields

Objectives

At the end of the lesson the student will be able to:

  • Use JLabels to display text
  • Use text fields for entering data

13.2.1: Using Labels

  • A JLabel is typically used to display text in a GUI
  • These labels often display text for other components
  • For instance, you may want a label for a text field

Code to Add Labels

  • Following code adds a label to a panel
  • JLabel label = new JLabel("Label text");
    JPanel panel = new JPanel();
    panel.add(label);
    
  • Other constructors of a JLabel allow Icons as well

Some Commonly-Used Constructors and Methods from JLabel

Constructor/Method Description
JLabel() Creates a blank label.
JLabel(Icon) Creates a label with the specified image.
JLabel(String) Creates a label with the specified text.
setIcon(Icon) Sets the icon for a label.
setHorizontalAlignment(int) Sets the alignment along the X axis, Usually JLabel.LEFT, JLabel.CENTER,or JLabel.RIGHT.
setText(String) Sets the text for a label.

For Example

  • In the following, we use this image for an icon: A pretty but meaningless splat (From the Java Tutorial)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LabelApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 150, HEIGHT = 125;

    public LabelApp() {
        super("Label Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        ImageIcon icon = new ImageIcon("icon.gif",
            "A pretty but meaningless icon");
        JLabel label1 = new JLabel("Text-only label");
        JLabel label2 =
            new JLabel("Image and text label");
        label2.setIcon(icon);
        label2.setHorizontalAlignment(JLabel.CENTER);
        JLabel label3 = new JLabel(icon);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(label1, BorderLayout.NORTH);
        panel.add(label2, BorderLayout.CENTER);
        panel.add(label3, BorderLayout.SOUTH);

        Container contentPane = getContentPane();
        contentPane.add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new LabelApp();
    }
}

Further Information

13.2.2: Displaying Images on JLabels

  • An easy way to display images is to use an ImageIcon object with a JLabel
  • ImageIcons can be created from either files or URLs
  • ImageIcon myImage = new ImageIcon("image.jpg");
    
  • Note that Java only supports GIF, JPEG and PNG images
    • If you have images in other formats, you will need to convert them
  • We use the ImageIcon to instantiate a JLabel
  • JLabel label = new JLabel(myImage);
    
  • We then add the JLabel to the application in the usual way

Example: Displaying an Image

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

public class ImageDisplayer extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 400;

    public ImageDisplayer() {
        super("Image Display Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        ImageIcon myImage = new ImageIcon("image.jpg");
        JLabel label = new JLabel(myImage);
        Container contentPane = getContentPane();
        contentPane.add(label);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new ImageDisplayer();
    }
}

We can download an image from my homepage and save it as image.jpg.

13.2.3: Using Text and Password Fields

  • JTextField: single-line area in which user can enter text
  • JPasswordField: extends JTextField and hides characters that a user enters
  • When the user presses the Enter key inside a JTextField, the component generates an ActionEvent
  • Thus, you can use an ActionListener to listen for text actions
  • Alternatively, you can add buttons to perform actions

Code for Text Fields

  • Code to declare a JTextField and a JPasswordField
  • JTextField login = new JTextField(10);
    JPasswordField password = new JPasswordField("asecret");
    
  • Code to register the handlers
  • login.addActionListener(this);
    password.addActionListener(this);
    
  • Example code that works with text and password fields
  • String data = login.getText();
    String pass = password.getPassword();
    password.setText("asecret");
    login.setEditable(false);
    

Commonly-Used Constructors and Methods from JTextField

Constructor/Method Description
JTextField(int) Creates an empty text field with the specified number of columns.
JTextField(String, int) Creates a text field that starts with the text and contains the number of columns.
getText() Returns the text contained in the text field as a String object.
setText() Sets the text field to the specified String.
setColumns(int) Sets the number of columns for the text field.
setEditable(boolean) Sets whether this text field is editable or not.

Commonly-Used Constructors and Methods from JPasswordField

Constructor/Method Description
JPasswordField(int) Creates an empty text field with the specified number of columns.
JTextField(String, int) Creates a password field that starts with the text and contains the number of columns.
getPassword() Returns the text stored in the component as a char[].

For Example

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

public class LoginDemo extends JFrame
        implements ActionListener {

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public LoginDemo() {
        super("Login Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel loginPanel = new JPanel();
        loginPanel.add(loginLabel);
        loginPanel.add(login);

        JLabel pwdLabel = new JLabel("Password:");
        password = new JPasswordField("asecret", 10);
        JPanel pwdPanel = new JPanel();
        pwdPanel.add(pwdLabel);
        pwdPanel.add(password);

        loginButton = new JButton("Press to Login");

        Container contentPane = getContentPane();
        contentPane.add(loginPanel, BorderLayout.NORTH);
        contentPane.add(pwdPanel, BorderLayout.CENTER);
        contentPane.add(loginButton, BorderLayout.SOUTH);

        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);

        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if (e.getSource() == password) {
            checkLogin();
            login.requestFocus();
        } else if (e.getSource() == loginButton) {
            checkLogin();
            login.requestFocus();
        }
    }

    public void checkLogin() {
        JOptionPane.showMessageDialog(null,
            "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword()),
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) {
        new LoginDemo();
    }
}
  • Note how the loginLabel and login text field are grouped into a JPanel
  • The pwdLabel and password field are grouped similarly
  • This keeps these components grouped together during frame resizing

13.2.4: Summary

  • A JLabel is commonly used to display text or images in a GUI
  • An image is loaded using an ImageIcon
  • A JTextField provides a single line area for users to type information
  • A JPasswordField extends JTextField and hides characters that a user enters
  • Grouping labels and text fields keeps associated components together during resizing

Exercise 13.2

  1. Compile and run the LoginDemo application shown below.
  2. Q1: What does the pack() method do?

    Q2: What does the statement password.requestFocus() do?

  3. Change the action in the code to display the message, "You successfully logged in", but only if the user enters the user name "cs12" and the password "asecret". Otherwise, display the message, "Login failed".
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginDemo extends JFrame
        implements ActionListener {

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public LoginDemo() {
        super("Login Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel loginPanel = new JPanel();
        loginPanel.add(loginLabel);
        loginPanel.add(login);

        JLabel pwdLabel = new JLabel("Password:");
        password = new JPasswordField("asecret", 10);
        JPanel pwdPanel = new JPanel();
        pwdPanel.add(pwdLabel);
        pwdPanel.add(password);

        loginButton = new JButton("Press to Login");

        Container contentPane = getContentPane();
        contentPane.add(loginPanel, BorderLayout.NORTH);
        contentPane.add(pwdPanel, BorderLayout.CENTER);
        contentPane.add(loginButton, BorderLayout.SOUTH);

        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);

        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if (e.getSource() == password) {
            checkLogin();
            login.requestFocus();
        } else if (e.getSource() == loginButton) {
            checkLogin();
            login.requestFocus();
        }
    }

    public void checkLogin() {
        JOptionPane.showMessageDialog(null,
            "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword()),
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) {
        new LoginDemo();
    }
}

13.3: Applets and the Web

Objectives

At the end of the lesson the student will be able to:

  • Discuss the technologies used on the Web
  • Describe the uses and limitations of applets
  • List the four important applet methods called by the browser

13.3.1: The Internet and the Web

What is the Internet?

  • Internet is a set of networks connected together with routers
  • Networks move data from one computer to another
  • Routers are computers that move the data from one network to another

What is the World-Wide Web?

  • The Web delivers hypertext documents over the Internet
  • Hypertext documents are written using Hypertext Markup Language (HTML)
  • Key feature of HTML is the hypertext link
  • Hypertext links connect one document to another

Brief History of the Internet

  • 1969: Internet started by US DOD with 4 computers -- called ARPANET
  • 1983: Internet (1000 computers) split into two parts -- military and University
  • 1987: High-speed backbone added to solve performance issues (10K computers)
  • 1989: World-Wide Web and HTML invented by Tim Berners-Lee at CERN
  • 1992-3: US Government decides to commercialize Internet
  • 1993: first graphical browser invented by Marc Andreessen
    • While a student at the University of Illinois

13.3.2: Web Technology

World-Wide Web Architecture

  • The web has four major parts:
    • Web client (e.g. browser): requester of documents and services
    • Web server: provider of services e.g. Web documents
    • Internet: very large network to move the data
    • Files: text, images, sound, video, etc.
  • Browser uses Hypertext Markup Language (HTML) to format a page

Web Browser

  • Web browser is an application program that runs on a computer
  • Allows a person to retrieve and display files in various formats
  • For example:
    • Display a text file in HTML format
    • Display picture files that use Graphics Interchange Format (GIF) format
    • Play a sound file in Windows Waveform (WAV) format

HTML

  • HTML files are a mixture of text for display and HTML tags
  • Tags are coded commands that tell the browser how to format the text
  • For example, HTML tags could define text size or color
  • For instance, the following HTML tag changes the text color of red dog
  • <font color="red">red dog</font>
  • HTML tags are shown in bold above
  • Note that tags begin with a less-than sign and end with a greater-than sign

Web Server

  • Web servers are programs that provide web documents
    • Often run on dedicated computers, also known as web servers
  • Web server software runs constantly in the background waiting for requests
  • When a request is received, the server locates and sends the requested document

Client/server Interaction

  • User enters a query, specified by a URL, into a client (browser)
  • The client connects to server and sends a query to a server
  • The server analyzes the query, computes results and respond with information
  • The client receives results and displays them to user

13.3.3: Introduction to Applets

Static Documents

  • At first, only static documents were available on the web
  • Soon became apparent that more technologies were needed
  • Wanted to display dynamic content in browsers
    • Graphics
    • Animation
    • Sound

Enter Applets

  • In 1995, Sun Microsystems released Applets
  • Applet: a Java program that runs in a browser
  • People were impressed with applets in web pages
    • Spinning molecules
    • Sorting demos
  • Both Netscape and Microsoft agreed to support Java applets

Advantages of Applets

  • Applets have several advantages when run in a Web browser
    • Applets work on the client and do not use server resources
    • Applets run in most browsers on most operating systems
    • Can use the full power of the Java programming language
    • Applets are secure, running with tight "sandbox" controls
    • Applets can communicate with the web server

Demonstration Applets

  • Sun has many demonstration applets
  • Can study and mimic source code to learn new features
  • All programmers can learn by reading the source code of existing programs

13.3.4: Applet Deployment Issues

  • When Java 1.0 was released, both IE and Netscape included a JVM
    • Allowed any Web page to run applets
  • Unfortunately, neither browser kept up with newer versions of Java
  • Because of this, while most browsers support Java 1.0, only a few support Java 1.1
    • Thus, most do not support Swing
    • Nor do most of them support recent Java features
  • To allow IE and Netscape to run newer versions of Java, Sun provides a Java Plug-in
  • If the Java Plug-in is installed, the browser can run Swing applets
  • Of course, many Web users have not installed the Java Plug-in
    • People need a strong incentive to bother installing any plug-in
  • Note that the Java Plug-in was automatically installed when you installed Java for this course

Two Solutions

  • One solution is to use Swing applets and install the Java Plug-in
    • On every client machine
  • Another solution is to write applets using the older AWT version of Java

Swing Applets

    Pros

  • Swing applets use Swing components
    • More features
    • Common look and feel
  • Can use all of the latest Java language features
  • Cons

  • Must install the Java Plug-in on client machines
  • Developer must run an HTML Converter program

AWT Applets

    Pros

  • Do not need to install the Java Plug-in on client machines
  • Developer does not need to run an HTML Converter program
  • Cons

  • Cannot use Swing components and the Swing event model
  • Must restrict Java features to earliest Java releases (e.g. version 1.0)

Guidelines and Advice

  • Use Swing on Intranets and places where you can be sure the Java Plug-in is installed
  • Use Swing if people have a strong enough interest in your program to install the Java Plug-in
  • Otherwise, use AWT

13.3.5: Applet Security Issues

  • Sun wanted to make sure applets could not damage a client system
  • Built strong security restrictions into applets to prevent problems

Applet Restrictions

  • Cannot read, write or delete files on the client system
  • Cannot run programs on the client system
  • Can only access a few properties of the client system:
    • Java version
    • Name of operating system
    • Version of operating system
    • Characters used to separate directories, paths and lines
  • Cannot make network connections to servers
    • Other than the server from which the applet was loaded

Some Applet Capabilities

  • Display GUI components, graphics and sound
  • Send keystrokes and mouse clicks to the applet's server
  • Make network connections to the applet's server
  • Call public methods of other applets on the same Web page

Removing Restrictions

  • You can create signed applets to overcome security restrictions
    • Indicates applet comes from a trusted source
  • User must agree to use a signed applet
    • Unless a policy file is setup by the client
    • In which case, no prompting occurs

More Information

13.3.6: Applet Construction

Inheritance Chain

  • Following is the inheritance chain for applets
  • Use methods of Component and Container with both types of applets
  • Extend Applet class to create AWT applets
  • Extend JApplet class to create Swing applets
java.awt.Component
  |
  +--java.awt.Container
       |
       +--java.awt.Panel
            |
            +--java.applet.Applet
                 |
                 +--javax.swing.JApplet

Applet Lifecycle Methods

  • Four methods are used to control the execution of an applet
    • All four are methods of the Applet class
  • Browser automatically calls these methods
    • You never need to call them
  • Normally you override the init() method in your applet code
  • You may also override the other methods

Four Methods of Applet

Method Description
public void init() Called when the browser loads the applet.
public void start() Called after the init method and every time the user moves to the web page with the applet.
public void stop() Called before the destroy method and every time the user leaves the web page with the applet.
public void destroy() Called when the user exits the browser.

13.3.7: Sample Applet

  • You can easily create an applet like the following
  • Code for this applet is:
  • import javax.swing.*;
    
    public class HelloApplet extends JApplet {
        public void init() {
            JLabel label = new JLabel("Hello, world!");
            getContentPane().add(label);
        }
    }
    
  • Looking at each piece of code:
  • import javax.swing.*;
    
  • JApplet is part of the Swing class-library
  • Use an import statement to access the library
  • public class HelloApplet extends JApplet {
    
  • Use and override methods defined in JApplet
  • Using inheritance, we can take advantage of the work someone else did
  • public void init() {
    
  • Applets start in init(), unlike applications which start in main()
  • By default, init() has an empty body
  • We override (redefine) init in our HelloApplet class
  • JLabel label = new JLabel("Hello, Applet World!");
    
  • For our simple Applet we only need to display text
  • We use a label class named JLabel for that purpose
  • One of the constructors for JLabel takes our literal string parameter: "Hello, Applet World!"
  • getContentPane().add(label);
    
  • We add our JLabel component to the JApplet container
  • JApplet can now display the text we entered

Exercise 13.3

  1. Label this exercise: Exercise 13.3
  2. Complete the following exercises and write answers to any questions.

Exercises

  1. Which demonstration applet impresses you the most?
  2. Use this applet code and for answering the questions that follow:

    import javax.swing.*;
    
    public class HelloApplet extends JApplet {
        public void init() {
            JLabel label = new JLabel("Hello, world!");
            getContentPane().add(label);
        }
    }
    
  3. What type of applet is this: AWT or Swing? How can you tell?
  4. This class overrides the init() method; which ancestor class contains the method that is being overridden?
  5. How does the init() method get called?

13.4: Swing Applets

Objectives

At the end of the lesson the student will be able to:

  • Develop and test a Swing applet
  • Code the HTML page for an applet
  • View the applet in a browser and the Applet Viewer

13.4.1: Developing Swing Applets

There are two ways to develop Swing applets:

  1. Develop new applets from scratch
  2. Convert existing Swing applications to applets

Developing Swing Applets from Scratch

  1. Write the code and compile the Swing applet
  2. Write the HTML page for the applet
  3. Test the applet with the Applet Viewer
  4. Use the HTML Converter to convert the HTML for the applet
  5. Test the HTML page with a browser

Converting Swing Applications to Applets

  1. Extend the JApplet class rather than the JFrame class
  2. Convert the constructor of the JFrame to the init() method of the applet
  3. Remove any code that:
    • Sets the title, size and position of the frame
    • Closes or exits the frame or application

For Example

  • Convert the following code to run as an applet
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class LoginDemo extends JFrame
            implements ActionListener {
    
        private JTextField login;
        private JPasswordField password;
        private JButton loginButton;
    
        public LoginDemo() {
            super("Login Application");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
    
            JLabel loginLabel = new JLabel("User name:");
            login = new JTextField(10);
            JPanel loginPanel = new JPanel();
            loginPanel.add(loginLabel);
            loginPanel.add(login);
    
            JLabel pwdLabel = new JLabel("Password:");
            password = new JPasswordField("asecret", 10);
            JPanel pwdPanel = new JPanel();
            pwdPanel.add(pwdLabel);
            pwdPanel.add(password);
    
            loginButton = new JButton("Press to Login");
    
            Container contentPane = getContentPane();
            contentPane.add(loginPanel, BorderLayout.NORTH);
            contentPane.add(pwdPanel, BorderLayout.CENTER);
            contentPane.add(loginButton, BorderLayout.SOUTH);
    
            login.addActionListener(this);
            password.addActionListener(this);
            loginButton.addActionListener(this);
    
            pack();
            setVisible(true);
        }
    
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                checkLogin();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                checkLogin();
                login.requestFocus();
            }
        }
    
        public void checkLogin() {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    
        public static void main(String[] args) {
            new LoginDemo();
        }
    }
    
  1. Rename LoginDemo to LoginApplet
  2. Extend JApplet rather than JFrame
  3. public class LoginApplet extends JApplet
  4. Remove the main() method
  5. Convert the constructor to be the init() method
  6. public void init()
  7. Remove the title set by the call to super
  8. Remove the setDefaultCloseOperation(EXIT_ON_CLOSE) method call
  9. Remove the pack() and setVisible(true) method calls
  • End result looks like:
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class LoginApplet extends JApplet
            implements ActionListener {
        private JTextField login;
        private JPasswordField password;
        private JButton loginButton;
    
        public void init() {
            JLabel loginLabel = new JLabel("User name:");
            login = new JTextField(10);
            JPanel loginPanel = new JPanel();
            loginPanel.add(loginLabel);
            loginPanel.add(login);
    
            JLabel pwdLabel = new JLabel("Password:");
            password = new JPasswordField("asecret", 10);
            JPanel pwdPanel = new JPanel();
            pwdPanel.add(pwdLabel);
            pwdPanel.add(password);
    
            loginButton = new JButton("Press to Login");
    
            Container contentPane = getContentPane();
            contentPane.add(loginPanel, BorderLayout.NORTH);
            contentPane.add(pwdPanel, BorderLayout.CENTER);
            contentPane.add(loginButton, BorderLayout.SOUTH);
    
            login.addActionListener(this);
            password.addActionListener(this);
            loginButton.addActionListener(this);
        }
    
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                checkLogin();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                checkLogin();
                login.requestFocus();
            }
        }
    
        public void checkLogin() {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
    

    Actual Applet

    If you cannot see this applet, your browser may not be Java-enabled.

13.4.2: Creating an HTML Page for Applets

About HTML

  • Hypertext Markup Language (HTML) is the language used to create Web pages
  • Web page is just a text file with HTML tags added to it
  • Tags are embedded in the text to control page layout
  • Tags consist of:
    1. "<": opening character of a tag
    2. Command such as html, body or font
    3. ">": closing character of a tag
  • HTML tags are case insensitive: can use either upper or lower case
  • Note that World Wide Web Consortium (W3C) recommends lowercase tags
  • HTML is viewable in all text editors including Notepad
  • Note that most tags come in pairs: opening tag and closing tag
  • Can nest tags, but should close inner tags before closing outer tags

For Example

  • Following is a basic HTML document that includes an applet tag
  • <html>
    <head>
    <title>Login Applet</title>
    </head>
    
    <body>
    <h1>Login Applet</h1>
    <applet code="LoginApplet.class" width=200 height=100>
    If you cannot see this applet, your browser may not
    be Java-enabled.
    </applet>
    
    </body>
    </html>
    

    See it

  • One thing to note is you can view the source HTML of a web page

Some HTML Tags

Tag Description
<html></html> Marks the start and end of an HTML page.
<head></head> Marks the start and end of the section of a page that describes the entire document.
<title></title> Defines the title of an HTML page that appears in the title bar of the browser.
<body></body> Marks the start and end of the section that contains text, applets and other information to present.
<h1></h1> Displays the enclosed text as a level-1 (large) header.
<applet></applet> Defines an applet for display in a document. This tag is officially deprecated, but most browsers still support it.
<embed></embed> Defines a plug-in application within the document. Netscape uses this tag to define Swing applets.
<object></object> Defines an object within a document. IE uses this tag to define Swing applets.

Some Attributes of the Applet Tag

Attribute Description
code Specifies the name of the class file to execute.
codebase Specifies the pathname of the applet on the server.
width Specifies the width of the applet in pixels.
height Specifies the height of the applet in pixels.
archive Specifies the archive file (such as a JAR file) that contains class files and other resources.

Further Information

13.4.3: Running the Applet Viewer

  • Applet Viewer is included in the SDK
  • Lets you test an applet before running it in a browser
  • Following is our LoginApplet displayed in the Applet Viewer
  • Note that only the applet is displayed
  • All other text is ignored

Using the Command Prompt

  1. Open a console window or access the command prompt
  2. Change to the directory where the applet class file is located
  3. Type in the command appletviewer followed by the HTML file for the applet
  4. appletviewer LoginApplet.html

13.4.4: Using the Java Plug-in HTML Converter

  • Different browsers run applets using different tags
    • Embed tag for Netscape
    • Object tag for IE
  • Can set up HTML code so that both types of tags are supported
    • Allows applets to run in more browsers
  • Since coding the HTML is somewhat complex, Sun created a tool
    • Called the Java Plug-in HTML Converter
  • Tool is included with the SDK for this course

For Example

  • For our example, we will convert the LoginApplet.html file
  • <html>
    <head>
    <title>Login Applet</title>
    </head>
    
    <body>
    <h1>Login Applet</h1>
    <applet code="LoginApplet.class" width=200 height=100>
    If you cannot see this applet, your browser may not
    be Java-enabled.
    </applet>
    
    </body>
    </html>
    
  • Note that conversion only works for code within <applet> tags
  • Converted page will work for many browsers including Netscape and IE
  • Applet Viewer may not display correctly after the conversion

Using the Converter

  1. Open a console window or access the command prompt
  2. Change to the directory where the tool is located
    • Usually in the lib subdirectory of the Java installation
  3. Type in the following command
  4. java -jar htmlconverter.jar -gui
  5. Brings up the following dialog
  6. Click on the Browse... button to select files
  7. Click on the Convert... button to convert a file

See the page and view the source.

Further Information

13.4.5: Testing and Debugging a Swing Applet

  • You often need to test an applet to see if it works correctly in a browser
  • However, the browser will not show exceptions or print statements
  • Sun provides the Java Console to address these issues

Testing a Swing Applet

  • Start your web browser and run the applet
  • If it does not work correctly, start the Java Console
  • Can view any exceptions thrown in the console window
  • Also can add println statements to the code and view them in the console

Displaying the Java Console

  • How to display the Java Console depends on how you installed it
  • From the Windows task bar, double-click the Java Console icon
  • From IE, select the Tools menu and select Sun Java Console
  • From Netscape, select the Tools menu and of the Communicator menu
  • From Mozilla, select the Tools, Web Development and Java Console

Further Information

13.4.6: Executing as Applets or Applications

  • Previously, we converted applications to applets
  • Also can configure an applet to run as either an applet or application
    • Possible because a JApplet is a Component
    • Thus applets can run in a JFrame
  • Will use the LoginApplet for our example
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class LoginApplet extends JApplet
            implements ActionListener {
        private JTextField login;
        private JPasswordField password;
        private JButton loginButton;
    
        public void init() {
            JLabel loginLabel = new JLabel("User name:");
            login = new JTextField(10);
            JPanel loginPanel = new JPanel();
            loginPanel.add(loginLabel);
            loginPanel.add(login);
    
            JLabel pwdLabel = new JLabel("Password:");
            password = new JPasswordField("asecret", 10);
            JPanel pwdPanel = new JPanel();
            pwdPanel.add(pwdLabel);
            pwdPanel.add(password);
    
            loginButton = new JButton("Press to Login");
    
            Container contentPane = getContentPane();
            contentPane.add(loginPanel, BorderLayout.NORTH);
            contentPane.add(pwdPanel, BorderLayout.CENTER);
            contentPane.add(loginButton, BorderLayout.SOUTH);
    
            login.addActionListener(this);
            password.addActionListener(this);
            loginButton.addActionListener(this);
        }
    
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                checkLogin();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                checkLogin();
                login.requestFocus();
            }
        }
    
        public void checkLogin() {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
    

For Example

  1. Add a main method to the applet
  2. public static void main(String[] args)
  3. Within main, Instantiate a JFrame and set the title
  4. JFrame frame = new JFrame("Login Pane");
  5. Set the desired behavior for when the frame closes
  6. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  7. Create an instance of the applet
  8. LoginApp applet = new LoginApp();
  9. Add code to set the size
  10. public static final int WIDTH = 200;
    public static final int HEIGHT = 100;
    ...
    applet.setSize(WIDTH, HEIGHT);
    
  11. Call the init() and start() methods of the applet
  12. applet.init();
    applet.start();
    
  13. Add the applet to the frame
  14. frame.getContentPane().add(applet);
  15. Arrange and display the frame
  16. public static final int X_LOC = 100, Y_LOC = 100;
    ...
    frame.setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
    frame.pack();
    frame.setLocation(X_LOC, Y_LOC);
    frame.setVisible(true);
    
  • End result looks like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApp extends JApplet
        implements ActionListener {
    public static final int X_LOC = 100, Y_LOC = 100;
    public static final int WIDTH = 100;
    public static final int HEIGHT = 70;

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public void init() {
        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel loginPanel = new JPanel();
        loginPanel.add(loginLabel);
        loginPanel.add(login);

        JLabel pwdLabel = new JLabel("Password:");
        password = new JPasswordField("asecret", 10);
        JPanel pwdPanel = new JPanel();
        pwdPanel.add(pwdLabel);
        pwdPanel.add(password);

        loginButton = new JButton("Press to Login");

        Container contentPane = getContentPane();
        contentPane.add(loginPanel, BorderLayout.NORTH);
        contentPane.add(pwdPanel, BorderLayout.CENTER);
        contentPane.add(loginButton, BorderLayout.SOUTH);

        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if (e.getSource() == password) {
            checkLogin();
            login.requestFocus();
        } else if (e.getSource() == loginButton) {
            checkLogin();
            login.requestFocus();
        }
    }

    public void checkLogin() {
        JOptionPane.showMessageDialog(null,
            "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword()),
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Login Pane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        LoginApp applet = new LoginApp();
        applet.setSize(WIDTH, HEIGHT);
        applet.init();
        applet.start();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setLocation(X_LOC, Y_LOC);
        frame.setVisible(true);
    }
}

Actual Applet

If you cannot see this applet, your browser may not be Java-enabled.

Exercise 13.4

  1. Convert the HelloFrame3, shown below, to run as an applet.
  2. As an optional step, convert it to run as either an application or an applet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame3 extends JFrame
        implements ActionListener {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton helloButton;
    private JButton exitButton;

    public HelloFrame3() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        helloButton = new JButton("Hello");
        helloButton.addActionListener(this);
        exitButton = new JButton("Exit");
        exitButton.addActionListener(this);
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        Container contentPane = getContentPane();
        contentPane.add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == helloButton) {
            String msg = "Hey";
            JOptionPane.showMessageDialog(this, msg);
        } else if (source == exitButton) {
            System.out.println("Goodbye!");
            System.exit(0);
        } else {
            System.out.println("Unknown ActionEvent");
        }
    }

    public static void main(String[] args) {
        new HelloFrame3();
    }
}

Wrap Up

    Reminders

    Due Next Class: Sampler Project (12/6/04)

  • When class is over, please shut down your computer
  • There is no need to turn in this weeks exercises
  • Work on your project!

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: November 23 2004 @20:42:00