13: More GUI Topics

What We Will Cover


Illuminations

Questions from last class?

Project Questions?

  1. You should have finished your project design by now
  2. By next week you should have completed the first implementation

13.1: Structuring Event Handling Code

Learner Outcomes

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

  • Distinguish among an event, an event source, an event object, and an event listener
  • List four options for structuring the classes that implement the listener interface for an event
  • Explain the difference between an inner class and an anonymous inner class
  • Explain the benefit of using adapter classes rather than implementing listener interfaces

13.1.1: About Event Handling

  • Most GUI programs use events and event handlers
  • An event in a GUI is an object representing an action like:
    • Clicking a mouse button
    • Dragging the mouse
    • Pressing a key on the keyboard
    • Or any other event expected to produce an action

Event-Firing and Listening

event flow

Terminology

  • Firing an event: when an object creates an event object
  • Listener: an object that waits for events to occur
  • Event handler: a method that responds to an event

Event Classes

  • Event classes define events that are triggered when users do things
  • Components, like JButton, create the events in response to user actions
  • Following is an inheritance hierarchy of some Event classes:
java.lang.Object
  |
  +--java.util.EventObject
       |
       +--java.awt.AWTEvent
            |
            +--java.awt.event.ActionEvent
            |
            +--java.awt.event.AdjustmentEvent
            |
            +--java.awt.event.ItemEvent
            |
            +--java.awt.event.ComponentEvent
                 |
                 +--java.awt.event.ContainerEvent
                 |
                 +--java.awt.event.FocusEvent
                 |
                 +--java.awt.event.PaintEvent
                 |
                 +--java.awt.event.WindowEvent
                 |
                 +--java.awt.event.InputEvent
                      |
                      +--java.awt.event.KeyEvent
                      |
                      +--java.awt.event.MouseEvent

Event-listener Interfaces

  • To handle an event, an object must become an event listener
    implements ActionListener
  • So that any object can become a listener, Java uses interfaces to declare listeners
  • A listener has one or more methods that are called when events occur:
    public void actionPerformed(ActionEvent ae);
  • Event objects are passed to the listener by calling a listener method
  • Programmers implement the methods defined in the interface
  • While implementing the method, the programmer writes the event-handling code
  • A listener must register with an event-producing component
    exitButton.addActionListener(this);
  • Some of the commonly used listener interfaces are shown below
java.util.EventListener
  |
  +--java.awt.event.ActionListener
  |
  +--java.awt.event.AdjustmentListener
  |
  +--java.awt.event.ComponentListener
  |
  +--java.awt.event.ContainerListener
  |
  +--java.awt.event.FocusListener
  |
  +--java.awt.event.ItemListener
  |
  +--java.awt.event.KeyListener
  |
  +--java.awt.event.MouseListener
  |
  +--java.awt.event.MouseMotionListener
  |
  +--java.awt.event.TextListener
  |
  +--java.awt.event.WindowListener

13.1.2: Organizing Event Handling Code

  • The basic procedure for handling events is straightforward
    1. Implement the listener interface for the event in some class
    2. Register an instance of the listener class to the event source by calling the appropriate addeventListener method
    3. Code the required methods of the listener interface
  • The basic procedure for handling events is also very flexible
  • An event listener can be any object that implements the listener interface
  • As a result, you can place the event-handling code in many different locations
  • We will look at placing the code in the locations listed below
  • Along the way we learn about inner and anonymous inner classes

Some Options for Implementing the Listener Interface

  • Implement it in a JFrame or JPanel
  • Implement it in a separate class
  • Implement it in an inner class
  • Implement it as an anonymous inner class

13.1.3: Using the Component Container

  • One convenient way to implement a listener interface is in the container for the components generating the events
  • This is the technique we have used so far in our examples and it works well for containers like JFrame and JPanel
  • When using this technique, you implement the listener interface when coding the class:
    public class HelloFrame3 extends JFrame
            implements ActionListener {
    
  • Within the container class, you can specify the this keyword as the parameter to the method that registers the listener:
    helloButton.addActionListener(this);
    
  • Within the container class you code the methods required by the interface:
    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == helloButton) {
            JOptionPane.showMessageDialog(this, "Hello");
        } else if (source == exitButton) {
            System.out.println("Goodbye!");
            System.exit(0);
        } else {
            System.out.println("Unknown ActionEvent");
        }
    }
    
  • When you use this technique with multiple components, you can use the getSource() method to determine which component fired the event
  • The getSource() method of an event object returns the memory location of the object that generated the event
  • This allows you to compare the value returned by getSource() against references to components:
    Object source = ae.getSource();
    if (source == helloButton) {
        // now you know the helloButton was pressed
    }
    

Example Using the Component Container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
        add(panel);

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

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == helloButton) {
            JOptionPane.showMessageDialog(this, "Hey");
        } 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();
    }
}

13.1.4: Using Separate Classes

  • You can use separate classes for the components and the code that handles component events
  • Using this technique, you do not need to use getSource() to determine which component fired the event
  • Instead, each component has its own event handling class:
    class HelloButtonListener implements ActionListener
    
  • The major problem with this technique is that the event handler code does not have direct access to the component
  • As a result, you must provide a way for the event listener to access the component
  • The easiest way to do that is to pass the component reference to the constructor of event handler
  • Then you save the component reference as an instance variable:
    private JButton button;
    
    public HelloButtonListener(JButton buttonRef) {
        button = buttonRef;
    }
    
  • If the component needs to interact with other components, you will need to pass those references as well

Example Using Separate Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame4 extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    public HelloFrame4() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton helloButton = new JButton("Hello");
        helloButton.addActionListener(
            new HelloButtonListener(helloButton));
        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(
            new ExitButtonListener(exitButton));
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

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

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

class HelloButtonListener implements ActionListener {
    private JButton button;

    public HelloButtonListener(JButton buttonRef) {
        button = buttonRef;
    }

    public void actionPerformed(ActionEvent ae) {
        JOptionPane.showMessageDialog(button, "Hey");
    }
}

class ExitButtonListener implements ActionListener {
    private JButton button;

    public ExitButtonListener(JButton buttonRef) {
        button = buttonRef;
    }

    public void actionPerformed(ActionEvent ae) {
        System.out.println("Goodbye!");
        System.exit(0);
    }
}

Simplifying Listeners with Adaptor Classes

  • Some listener interfaces have many methods that must be implemented
  • For example, a WindowListener has seven methods that must be implemented
  • Yet, you often only want to use one of the methods
  • One way to simplify coding these listener interfaces is to use an adaptor class
  • An adaptor class implements all the methods of a listener interface with empty methods
  • For example, the WindowAdapter class looks something like:
    public void windowClosing(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    
  • Using an adaptor class, you can implement only those methods you need:
    import java.awt.event.*;
    
    public class WinHandler extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }
    
  • Java has adaptor classes for listener interfaces requiring more than one method

13.1.5: Using Inner Classes

  • One way to reduce the complexity of passing references to listener classes is to use an inner class
  • An inner class is a class that is contained within another class
  • An inner class has access to all members of its containing (outer) class
  • Thus inner classes are often a simpler solution for implementing event listeners

Example Using Inner Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame5 extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    public HelloFrame5() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton helloButton = new JButton("Hello");
        helloButton.addActionListener(
            new HelloButtonListener());
        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(
            new ExitButtonListener());
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

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

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

    class HelloButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            JOptionPane.showMessageDialog(
                HelloFrame5.this, "Hey");
        }
    }

    class ExitButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            System.out.println("Goodbye!");
            System.exit(0);
        }
    }
}

Notes on the Code

  • See how inner classes make the code more compact and simpler than when using separate classes
  • Also note that no conditional statements are required in the code
    • Unlike when using getSource() to separate events in the component container
  • In addition, note the reference to this in the outer class of HelloButtonListener
    HelloFrame5.this
  • This is the required syntax for accessing the this reference of the outer class
  • One final thing to note is how the compiler names the inner classes:
    HelloFrame5$ExitButtonListener.class
    HelloFrame5$HelloButtonListener.class
    
  • They are easily identified as inner classes from the file name

13.1.6: Using Anonymous Inner Classes

  • One other commonly used way to write handlers is to use an anonymous inner class
    • Usually just called an anonymous class
  • An anonymous class is a special type of inner class without a name
  • It is both declared and instantiated in one statement
  • The syntax is:
    new ListenerInterface() { class-body }
    
  • For example:
    helloButton.addActionListener(
        new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JOptionPane.showMessageDialog(
                    HelloFrame6.this, "Hey");
            }
        });
    

Example Using Anonymous Inner Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame6 extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    public HelloFrame6() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton helloButton = new JButton("Hello");
        helloButton.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(
                        HelloFrame6.this, "Hey");
                }
            });
        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Goodbye!");
                    System.exit(0);
                }
            });
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

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

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

Notes on the Code

  • As you can see the code is shorter than our original example
  • Thus anonymous classes make the code even more compact and simpler
  • Also note how the compiler names the inner classes:
    HelloFrame6$1.class
    HelloFrame6$2.class
    
  • An anonymous class is referred to by a number rather than a name
  • In addition, note that anonymous classes can implement adaptor classes
  • For example:
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e){
            System.exit(0);
    }});
    

13.1.7: Summary

  • An event is an object that is generated by user actions or by system events
  • An event listener is an object that implements a listener interface
  • To handle an event, you must:
    1. Implement the listener interface for the event in some class
    2. Register an instance of the listener class to the event source by calling the appropriate addeventListener method
    3. Code the required methods of the listener interface
  • The container for the for the components generating the events can also be the listener for the events
    • In that case, you specify this in the addeventListener() method
  • You can also use separate classes to listen for events
    • Using this technique, you do not need to use getSource() to determine which component fired the event
    • Instead, each component has its own event handling class
  • To reduce the amount of code needed for separate classes, Java provides adaptor classes for listener interfaces requiring more than one method
  • One commonly used technique for writing event listeners is to use an inner class
    • This reduces the complexity of using separate classes because an inner class has access to all members of its containing class
  • One other commonly used way to write handlers is to use an anonymous inner class
    • An anonymous class is a special type of inner class without a name
    • It is both declared and instantiated in one statement
      new ListenerInterface() { class-body }

Exercise 13.1

Take one minute to prepare answers to the following questions:

  1. What is the difference between an event, an event source, an event object, and an event listener?
  2. What are four options for structuring the classes that implement the listener interface for an event?
  3. What is the benefit of using adapter classes rather than implementing listener interfaces?
  4. What is the difference between an inner class and an anonymous inner class?

13.2: Low-level Events

Learner Outcomes

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

  • Discuss how the AWT Event Model works
  • Describe what is a Java interface
  • Write code to handle keyboard and mouse events

13.2.1: The AWT Event Model

  • So far we have worked with events generated by controls
  • Now we will learn how to work with low-level events such as mouse movement or key presses
  • Java uses what is known as the AWT Event Model to handle user input
  • AWT stands for Abstract Windowing Toolkit
  • AWT uses interchangeable toolkits that interact with the host windowing system
  • Every time a user presses a key or uses a mouse, the system tells the AWT about the event
  • Since many of these events can happen very quickly, AWT stores these events in a queue
    • A queue is a list of items that are processed in a first-in, first-out order
  • When the system has time, usually within a few milliseconds, the AWT sends the event information to the code that handles the event

Dispatching the Events

  • Where does the AWT send these events?
  • When an event occurs, the AWT checks to see if there are any listeners for the event
    • A listener is an object that receives the event information
  • If a listener is signed up to receive the event, the AWT sends it the event information
  • There is a different type of listener for every type of event
  • For instance, for a keyboard input event there is a KeyListener interface
  • The following is an example of how the AWT event model works for keyboard input

Event Model for Keyboard Input

  1. The user presses a key
  2. The operating system sends the keypress event to the JVM
  3. The JVM runtime puts the event in the AWT's event queue
  4. The AWT event dispatch thread dispatches the event to any KeyListeners
  5. Each KeyListener receives the key event and does whatever it is programmed to do

13.2.2: Handling Low-Level Events Using Interfaces

  • To handle low-level events, you need to implement an appropriate listener
  • An interface is like a class in some ways, but very limited
  • The following are some of the interfaces provided for low-level event handling

Some Interfaces for Event Handling

Interface Description
KeyListener Used to listen for KeyEvents that occur when a keyboard key is pressed.
MouseListener Used to listen for "interesting" MouseEvents such as button clicks.
MouseMotionListener Used to listen for MouseEvents where the mouse is moving or dragged.
MouseWheelListener Used to listen for a MouseWheelEvent, which indicates that the mouse wheel was rotated.
WindowListener Used to listens for WindowEvents that occur during a window's life.

13.2.3: Keyboard Input

  • A keyboard event occurs when a user presses, releases or presses and releases a key
  • To capture key events, you need to do two things:
    1. Create a KeyListener class
    2. Register the listener to receive events
  • To register a listener, just call the addKeyListener() method on the component that you want to receive key events on
  • For example, we could listen for key events on a JPanel component like we used for drawing:
    public class KeyTest extends JPanel implements KeyListener {
        [...]
        addKeyListener(this);
        [...]
    }
    
  • You can see the details in the example code at the end of this section

Writing a KeyListener

  • To create a KeyListener, you need to create an object that implements the KeyListener interface
  • The KeyListener interface has three methods: keyPressed(), keyReleased(), and keyTyped()
  • A "typed" event is like a key press but does not report keys that do not map to Unicode characters
  • For example, if we were to listen for all the events, and used Shift-A to get an uppercase A, we would see the following events reported:
    Pressed: Shift
    Pressed: A
    Typed: A
    Released: A
    Released: Shift
    
  • Each of the three methods has a KeyEvent parameter, as shown in the table below
  • You can use the KeyEvent object to inspect what key was pressed or released
  • You can see some of the commonly used methods in the table below
  • Note that the KeyEvent class inherits from InputEvent
  • Thus, you can use some methods of the InputEvent class as well
  • Note that the getKeyCode() method of the KeyEvent class returns an int code
  • All the codes are define in the KeyEvent class in the form of VK_xxx
  • For instance, the A key has the key code KeyEvent.VK_A

Methods of the KeyListener Interface

Method Description
keyPressed(KeyEvent e) Invoked when a key has been pressed.
keyReleased(KeyEvent e) Invoked when a key has been released.
keyTyped(KeyEvent e) Invoked when a key has been typed.

Commonly Used Methods of the KeyEvent Class

Method Description
getKeyChar() Returns a char that represents the key pressed.
getKeyCode() Returns an int code that represents the key pressed.

Commonly Used Methods of the InputEvent Class

Method Description
consume() Consumes and stops further processing of the event.
isAltDown() Returns a boolean that indicates if the Alt key is pressed.
isControlDown() Returns a boolean that indicates if the Ctrl key is pressed.
isShiftDown() Returns a boolean that indicates if the Shift key is pressed.

13.2.4: Working With Key Events

  • Now let us try working with key events
  • The KeyTest class shown below implements the KeyListener interface
  • If just displays key events to the screen
  • To exit the program, press the Escape key
  • Note that the program uses a JTextArea and a JScrollPane
  • You can use a JTextArea when you want to display or edit multiple lines of text
  • If you get too many lines of text, then you can add it to a JScrollPane
  • A JScrollPane adds horizontal or vertical scroll bars to a compatible component

Class KeyTest Demonstrating KeyEvent Handling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

/**
 * A simple keyboard test that displays keys events to the
 * screen. Useful for debugging key input as well.
 */
public class KeyTest extends JPanel implements KeyListener {
    public static final int WIDTH = 400, HEIGHT = 300;
    public static final int FONT_SIZE = 24;
    private static final int X = 5;

    private int keyCode;
    private char keyChar = ' ';

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a drawing panel and add it to the frame
        KeyTest panel = new KeyTest();
        frame.add(panel);

        // Set the frame size and make it visible
        frame.setSize(WIDTH, HEIGHT);
        frame.setVisible(true);
        panel.requestFocusInWindow(); // After visible
    }

    // Constructor
    public KeyTest() {
        setBackground(Color.BLUE);
        addKeyListener(this); // Make this object listen
        setFocusTraversalKeysEnabled(false); // Show Tab key
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setColor(Color.YELLOW);
        g.setFont(new Font("Dialog", Font.PLAIN, FONT_SIZE));

        int y = FONT_SIZE;
        g.drawString("Press a key (Esc to exit)...", X, y);
        y += FONT_SIZE + 2;
        g.drawString("Key code: " + keyCode, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Key char: " + keyChar, X, y);
    }

    // A method from the KeyListener interface
    public void keyPressed(KeyEvent e) {
        keyCode = e.getKeyCode();
        keyChar = ' ';
        if (keyCode == KeyEvent.VK_ESCAPE) {
             System.exit(0); // Exit the program
        }
        repaint(); // Signal AWT to repaint this window
        e.consume(); // Prevent other use of the key
    }

    // A method from the KeyListener interface
    public void keyReleased(KeyEvent e) {
        // Method not used for this application
        e.consume(); // Prevent other use of the key
    }

    // A method from the KeyListener interface
    public void keyTyped(KeyEvent e) {
        keyChar = e.getKeyChar();
        repaint(); // signal AWT to repaint this window
        e.consume(); // Prevent other use of the key
    }
}

Notes on Key Processing

  • Notice the call to requestFocusInWindow() method
    requestFocusInWindow(); // After "realized"
    
  • For a key press to be detected by the code in our window, the component must have the keyboard focus
  • The call to requestFocusInWindow() makes sure that our KeyTest frame gains the focus when the window is activated
  • Also notice the call to setFocusTraversalKeysEnabled(false)
  • This call disables the focus traversal keys.
  • The focus traversal keys allow a user to change the keyboard focus from one component to another
  • For example, on a web page you have probably used the Tab key to move from one field in a form to another
  • The Tab key is not the only key that can cause strange behavior
  • The Alt key can also cause problems
  • On most systems, the Alt key is used to activate a mnemonic:
    • A mnemonic is a shortcut or accelerator key for a particular user interface element
    • For example, pressing Alt+F activates the File menu on most applications that have a menu bar
  • The AWT thinks the next key pressed after Alt is a mnemonic and ignores the key
  • To prevent other problems, we stop every KeyEvent in each KeyListener from being processed in the default manner by calling:
    e.consume();

More Information

13.2.5: Mouse Input

  • A mouse is a more complicated device than a keyboard with more options
  • A mouse has buttons (one, two or three depending on the mouse), moves and usually a scroll wheel
  • This helps explain why you can receive three different types of mouse events:
    • Mouse button clicks
    • Mouse motion
    • Mouse wheel scrolls
  • Mouse buttons behave like keyboard buttons, but without the key repetition
  • Mouse motion is broken down into x and y screen coordinates
  • Finally, mouse wheel events tell how far the wheel was scrolled
  • Each mouse event type has its own listener:
    • MouseListener
    • MouseMotionListener
    • MouseWheelListener
  • Each listener has a MouseEvent parameter that you can use to find out information about the event
  • The MouseWheelListener interface has a MouseWheelEvent that inherits from a MouseEvent
  • In addition to the above listeners, Java 1.5 added the MouseInfo class
  • The MouseInfo class has two static methods that return the number of mouse buttons and the location of the mouse pointer

Methods of the MouseListener Interface

Method Description
mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released).
mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component.
mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component.
mouseEntered(MouseEvent e) Invoked when the mouse enters a component.
mouseExited(MouseEvent e) Invoked when the mouse exits a component.

Methods of the MouseMotionListener Interface

Method Description
mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. Events continue to be delivered to the component where the drag originated until the mouse button is released.
mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods of the MouseWheelListener Interface

Method Description
mouseWheelMoved(MouseWheelEvent e) Invoked when the mouse wheel is rotated.

Commonly Used Methods of the MouseEvent Class

Method Description
getButton() Returns an int code that represents which, if any, of the mouse buttons has changed state.
getPoint() Returns the x, y position of the event as a Point object.
getX() Returns the x-coordinate of the event.
getY() Returns the y-coordinate of the event.

Commonly Used Methods of the MouseWheelEvent Class

Method Description
getWheelRotation() Returns the number of "clicks" the mouse wheel was rotated. Negative values mean scrolling up, and positive values mean scrolling down.

Methods of the MouseInfo Class

Method Description
getNumberOfButtons() Returns the number of buttons on the mouse, or -1 if the system does not have a mouse.
getPointerInfo() Allows you to discover the desktop location of the mouse pointer.

13.2.6: Working With Mouse Events

  • Now let us try working with mouse events
  • The MouseTest class shown below implements all three mouse interfaces
  • The program draws a message at the location of the cursor
  • By clicking the mouse, you can change the message
  • Also, by rotating the mouse wheel, you can change the foreground colors

Class MouseTest Demonstrating MouseEvent Handling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * A simple mouse test that displays information from
 * mouse events.
 */
public class MouseTest extends JPanel implements
        MouseListener, MouseMotionListener,
        MouseWheelListener {
    public static final int WIDTH = 400, HEIGHT = 300;
    public static final int LOC_X = 50, LOC_Y = 50;
    public static final int FONT_SIZE = 24;
    public static final int X = 10;
    private static final Color[] COLORS = {Color.WHITE,
        Color.RED, Color.ORANGE, Color.YELLOW, Color.CYAN};
    private int colorIndex;

    // Mouse event variables
    private int clickX, clickY;
    private int pressX, pressY;
    private int releaseX, releaseY;
    private int enterX, enterY;
    private int exitX, exitY;
    private int dragX, dragY;
    private int moveX, moveY;
    private int clickedButton, pressedButton, releasedButton;
    private int wheelClicks;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MouseTest panel = new MouseTest();
        frame.add(panel);

        frame.setBounds(LOC_X, LOC_Y, WIDTH, HEIGHT);
        frame.setVisible(true);
    }

    // Constructor
    public MouseTest() {
        setBackground(Color.BLUE);
        setForeground(Color.WHITE);
        addMouseListener(this);
        addMouseMotionListener(this);
        addMouseWheelListener(this);
    }

    // Display everything
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Draw background
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());

        // Setup font
        g.setColor(getForeground());
        g.setFont(new Font("Dialog", Font.PLAIN, FONT_SIZE));

        // Display the mouse info
        int y = FONT_SIZE;
        g.drawString("Mouse entered at " + enterX + ", "
            + enterY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse exited at " + exitX + ", "
            + exitY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse pressed " + pressedButton
            + " at " + pressX + ", " + pressY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse released " + releasedButton
            + " at " + releaseX + ", " + releaseY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse clicked " + clickedButton
            + " at " + clickX + ", " + clickY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse dragged at " + dragX + ","
            + dragY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse moved at " + moveX + ", "
            + moveY, X, y);
        y += FONT_SIZE + 2;
        g.drawString("Mouse rotated " + wheelClicks
            + " wheel clicks", X, y);
    }

    // From the MouseListener interface
    public void mouseClicked(MouseEvent e) {
        clickX = e.getX();
        clickY = e.getY();
        clickedButton = e.getButton();
        repaint(); // something changed so repaint
    }

    // From the MouseListener interface
    public void mouseEntered(MouseEvent e) {
        enterX = e.getX();
        enterY = e.getY();
        repaint();
    }

    // From the MouseListener interface
    public void mouseExited(MouseEvent e) {
        exitX = e.getX();
        exitY = e.getY();
        repaint();
    }

    // From the MouseListener interface
    public void mousePressed(MouseEvent e) {
        pressX = e.getX();
        pressY = e.getY();
        pressedButton = e.getButton();
        repaint();
    }

    // From the MouseListener interface
    public void mouseReleased(MouseEvent e) {
        releaseX = e.getX();
        releaseY = e.getY();
        releasedButton = e.getButton();
        repaint();
    }

    // From the MouseMotionListener interface
    public void mouseDragged(MouseEvent e) {
        dragX = e.getX();
        dragY = e.getY();
        repaint();
    }

    // From the MouseMotionListener interface
    public void mouseMoved(MouseEvent e) {
        moveX = e.getX();
        moveY = e.getY();
        repaint();
    }

    // From the MouseWheelListener interface
    public void mouseWheelMoved(MouseWheelEvent e) {
        wheelClicks = e.getWheelRotation();
        // Change colors
        colorIndex = (colorIndex + wheelClicks)
            % COLORS.length;
        if (colorIndex < 0) {
            colorIndex += COLORS.length;
        }
        setForeground(COLORS[colorIndex]);
        repaint();
    }
}

More Information

13.2.7: Summary

  • Java uses the AWT Event Model to handle user input
  • So far we have worked with events generated by controls
    • Sometimes called high-level events
  • In your program, you may want to work directly with low-level events like key presses and mouse movement
  • To capture key events, you need to do two things:
    1. Create a KeyListener class
    2. Register the listener to receive events
  • We looked at how to do this and showed an example
  • We also looked at how to capture and handle mouse events
  • A mouse is more complicated than a keyboard and so it had more interfaces

Check Yourself

  1. How does the AWT Event Model work?
  2. What interface do you need to implement for listening to keyboard events?
  3. What method does your JFrame component need to call to receive keyboard events?
  4. What interfaces do you need to implement for listening to mouse events?

Exercise 13.2

Take one minute to review the Check Yourself questions. We will review the questions after you are ready.

13.3: Applets and the Web

Learner Outcomes

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

  • Networking is about moving data from one computer to another
  • Internet: a set of networks connected together with routers
  • Routers: special computers that move data between networks
  • All computers on the Internet talk to each other using the Internet Protocol (IP)

A 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: Tim Berners-Lee started developing HTTP and HTML Web pages
  • 1991: CERN publicizes the new World Wide Web project
  • 1993: First graphical browser (Mosaic) invented by Marc Andreessen and Eric Bina
  • 1995: Internet opened to commercial interests
  • 1998: E-commerce becomes a "hot" technology
  • 2000: Start of the "dotcom" crash
  • 2006: Information technology jobs return to pre-crash levels (personal observation)

About the World-Wide Web

  • Researchers at CERN developed a system of interconnected documents using hypertext
    • Documents are stored on computers called servers
    • Using the Internet, you can access documents from client computers
  • One of the innovations of the web was hypertext
    • Hypertext allows users to click items called links to open documents
    • Using links allowed users to move around the Internet without needing to know the address of a document
  • Documents on the world-wide web are known as web pages
    • Each page can contain images, video and sound clips
    • All files are stored on web servers
  • A web browser is used to view a web page
  • You can see an example of how this works in the following image

Retrieving web documents

13.3.2: Web Technology

World-Wide Web Architecture

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

Web Browser

  • Web browser is a 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

  • A web page is a text file written in Hypertext Markup Language (HTML)
  • HTML is a markup language that describes the structure and content of a document
  • A markup language combines text and extra information about the text
  • In HTML, the extra information is coded as HTML tags
  • HTML tags are coded commands that describe the structure of the text
  • For example, one HTML tag is the paragraph which has the syntax:
    <p>content</p>
  • For example:
    <p>Some example text content for display</p>
    
  • Which displays the following output:

    Some example text content for display

  • 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 a web server
  • Web server software runs constantly in the background waiting for requests
  • When a request is received, locates and sends the requested document

Client/server Interaction

  • The user enters a request into their browser ussing a URL
  • The browser (client) connects to a server and requests the page
  • The server responds the the request with the specified information
  • The browser receives the response and display the data to the user
world-wide web

13.3.3: Introduction to Applets

  • At first, only static documents were available on the Web
  • People soon wanted more documents and types of media such as:
    • Graphics
    • Animation
    • Sound

Enter Java Applets

  • In 1995, Sun Microsystems released Applets
  • Applet: a program that runs inside another program (such as a browser)
  • People were impressed with Java applets in Web pages
  • 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

  • Gyan Labs: Example of modern Java applets
  • Sun has many demonstration applets
  • You can study the source code to learn how they work
  • 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, not all support later versions
  • 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:
    • More features
    • Common look and feel on all platforms (Windows, Mac OS and Linux)
    • Must install the Java Plug-in on every client machine
  • Another solution is to write applets using the older AWT version of Java
    • Do not need to install the Java Plug-in on client machines
    • Cannot use Swing components and event model
    • Must restrict Java features to earliest Java releases (e.g. version 1.0)
  • Yet another strategy is to use older versions of Java, but not the oldest
  • Most Java-enabled browsers have version 1.1 or newer installed

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 an older version of Java, such as 1.1, or AWT

More Information

13.3.5: Applet Security Issues

  • Sun wanted to make sure applets could not damage a client system
  • Thus it built strong security restrictions into applets to limit what they can do

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 one sending the applet

Some Applet Capabilities

  • Display GUI components and graphics
  • Play videos and sounds
  • Make network connections to the applet's server
  • Call public methods of other applets on the same Web page

Bypassing Security

  • You can create signed applets to overcome security restrictions
    • Indicates applet comes from a trusted source
  • User must agree to use a signed applet
  • Further information: Chapter 10: Signed Applets

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 override the init() method in your applet code
  • 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:
1
2
3
4
5
6
7
8
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 an init() method, 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, 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, World!"
    getContentPane().add(label);
    
  • We add our JLabel component to the JApplet container
  • JApplet can now display the text we entered

Exercise 13.3

Take one minute to review the Check Yourself questions. We will review the questions as time permits.

Check Yourself

Use this applet code and for answering the questions that follow:

1
2
3
4
5
6
7
8
import javax.swing.*;

public class HelloApplet extends JApplet {
    public void init() {
        JLabel label = new JLabel("Hello, world!");
        getContentPane().add(label);
    }
}
  1. What type of applet is this: AWT or Swing? How can you tell?
  2. How does the init() method get called?
  3. Using Java 1.5 or later, how could you rewrite line 6?

13.4: Swing Applets

Learner Outcomes

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 the code for Swing applets:
    • Develop code for new applets from scratch
    • Convert existing Swing applications to applets

Developing Swing Applets

  1. Write or convert 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 program 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:
    • If your application extends a JPanel, then add your panel to a JApplet instead of a JFrame
  2. Convert the constructor of the JFrame to the init() method of JApplet
    • Constructors are called first and the full applet environment is not available until init() is called
    • Thus some methods, like image loading methods, do not work until init() is called
  3. If you override paintComponent(), then override paint() instead
    • JApplet does not have a paintComponent() method
  4. Remove any code that:
    • Exits the frame
    • Sets the title, size, position or visibility of the GUI

Example Converting an Application to an Applet

  1. Rename LoginPane to LoginApplet
  2. Extend JApplet rather than JFrame:
    public class LoginApplet extends JApplet
    
  3. Remove the main() method
  4. Recode the constructor to an init() method:
    public void init()
  5. Remove the call to super() since it sets the title
  6. Delete the call to setDefaultCloseOperation(EXIT_ON_CLOSE)
  7. Remove the calls to setLocation(X_LOC, Y_LOC), pack() and setVisible(true)

Original Application Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginPane extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100;
    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

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

    public LoginPane() {
        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");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);

        add(loginPanel, BorderLayout.NORTH);
        add(pwdPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        LoginListener listener = new LoginListener();
        login.addActionListener(listener);
        password.addActionListener(listener);
        loginButton.addActionListener(listener);

        setLocation(X_LOC, Y_LOC);
        pack();
        setVisible(true);
    }

    private void showMessage() {
        String message = "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword());
        JOptionPane.showMessageDialog(null, message,
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);

    }

    class LoginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                showMessage();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                showMessage();
                login.requestFocus();
            }
        }
    }
}

Converted Applet Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApplet extends JApplet {
    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public void init() {
        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel LoginAppletl = new JPanel();
        LoginAppletl.add(loginLabel);
        LoginAppletl.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");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);

        add(LoginAppletl, BorderLayout.NORTH);
        add(pwdPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        LoginListener listener = new LoginListener();
        login.addActionListener(listener);
        password.addActionListener(listener);
        loginButton.addActionListener(listener);
    }

    private void showMessage() {
        String message = "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword());
        JOptionPane.showMessageDialog(this, message,
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);

    }

    class LoginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                showMessage();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                showMessage();
                login.requestFocus();
            }
        }
    }
}

Actual Applet

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

13.4.2: Creating an HTML Page for Applets

  • After you have applet code, you have to view it using a browser
  • To view applets in a browser, you first need to write some HTML code

About HTML

  • Hypertext Markup Language (HTML) is the language used to create Web pages
  • A web page is just a text file with HTML tags added
  • Tags are embedded in the text to control page layout
  • Tags consist of:
    1. "<": opening character of a tag
    2. A layout instruction such as html, body or font
    3. ">": closing character of a tag
  • HTML tags are case insensitive: you can use either upper or lower case
  • You can use any text editor to view HTML including Notepad and TextPad
  • Note that most tags come in pairs: opening tag and closing tag
  • Also, you can nest tags, but always close inner tags before closing outer tags

For Example

  • Following is a basic HTML document that includes an applet tag
  • One thing to note is you can view the source HTML of a web page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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

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

    login 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:
    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
  • You can set up HTML code so that both types of tags are supported
    • Supporting both tags 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
    • You can find the tool in the bin subdirectory of your Java installation
  • A converted page will work for most browsers including Mozilla, Netscape and IE

Instructions for and Example of Using the HTML Converter

  • For our example, we will convert the LoginApplet.html file shown below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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>
  1. Save the HTML code to a convenient location like your Desktop (or Home) directory
  2. Locate the HtmlConverter.exe program and start the application.
    • Located in the jdk/bin subdirectory of the Java installation
  3. Click on the Browse... button and find the HTML file to convert.
  4. Click on the Convert... button to convert the HTML file

converter

See the converted page and view the source.

  • Note that you may have to adjust the width or height specified in the HTML because the applet viewer adds a border to the display area and a browser does not
  • Also note that the Applet Viewer may not display correctly after the conversion

More Information

13.4.5: Testing and Debugging an Applet

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

Testing a Java Applet

  • Start your web browser and run the applet
  • If it does not work correctly, start the Java Console
  • You can view any exceptions thrown by the applet in the console window
  • Also you can add System.out.println() statements to the code and view them in the console

Displaying the Java Console

  • How to display the Java Console depends both on how you installed it and your browser
  • If it shows in 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
  • Firefox requires that you install an extension to view the console
    • I used Web Developer which includes a Java Console among its other tools

Further Information

13.4.6: Executing as Applets or Applications

  • Previously, we converted applications to applets
  • However, you can configure an applet to run as either an applet or application
    • This is possible because a JApplet is a Component
    • You can add any Component to a JFrame
  • We will convert the LoginApplet to run as either an applet or application

Example to Convert: LoginApplet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApplet extends JApplet {
    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public void init() {
        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel LoginAppletl = new JPanel();
        LoginAppletl.add(loginLabel);
        LoginAppletl.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");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);

        add(LoginAppletl, BorderLayout.NORTH);
        add(pwdPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        LoginListener listener = new LoginListener();
        login.addActionListener(listener);
        password.addActionListener(listener);
        loginButton.addActionListener(listener);
    }

    private void showMessage() {
        String message = "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword());
        JOptionPane.showMessageDialog(this, message,
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);

    }

    class LoginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                showMessage();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                showMessage();
                login.requestFocus();
            }
        }
    }
}

Example Converting to Run as Either an Applet or Application

  1. Add a main method to the applet:
    public static void main(String[] args)
  2. Within main(), instantiate a JFrame and set the title:
    JFrame frame = new JFrame("Login Pane");
  3. Set the desired behavior for when the frame closes:
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
  4. Create an instance of the applet:
    LoginApp applet = new LoginApp();
  5. Call the init() and start() methods of the applet:
    applet.init();
    applet.start();
    
  6. Add the applet to the frame:
    frame.add(applet);
  7. Arrange, size and display the frame:
    frame.pack();
    frame.setVisible(true);
    

Example of Converted Applet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApp extends JApplet {
    public static final int X_LOC = 100, Y_LOC = 100;

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

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

    public void init() {
        JLabel loginLabel = new JLabel("User name:");
        login = new JTextField(10);
        JPanel LoginAppl = new JPanel();
        LoginAppl.add(loginLabel);
        LoginAppl.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");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);

        add(LoginAppl, BorderLayout.NORTH);
        add(pwdPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        LoginListener listener = new LoginListener();
        login.addActionListener(listener);
        password.addActionListener(listener);
        loginButton.addActionListener(listener);
    }

    private void showMessage() {
        String message = "Login: " + login.getText()
            + "\nPassword: "
            + new String(password.getPassword());
        JOptionPane.showMessageDialog(this, message,
            "Login Message",
            JOptionPane.INFORMATION_MESSAGE);

    }

    class LoginListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == login) {
                password.requestFocus();
            } else if (e.getSource() == password) {
                showMessage();
                login.requestFocus();
            } else if (e.getSource() == loginButton) {
                showMessage();
                login.requestFocus();
            }
        }
    }
}

Actual Applet

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

Exercise 13.4

In this exercise we examine how to run an application as an applet.

Specifications

  1. Convert the HelloFrame5 application, shown below, to run as an applet.
  2. As an optional step, convert it to run as either an application or an applet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame5 extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    public HelloFrame5() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton helloButton = new JButton("Hello");
        helloButton.addActionListener(
            new HelloButtonListener());
        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(
            new ExitButtonListener());
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

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

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

    class HelloButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            JOptionPane.showMessageDialog(
                HelloFrame5.this, "Hey");
        }
    }

    class ExitButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            System.out.println("Goodbye!");
            System.exit(0);
        }
    }
}

Check Yourself

  1. How can the code for a Swing application be converted to a Swing applet?
  2. How is an applet placed in an HTML page?
  3. What is the Applet Viewer?
  4. How can debugging information be displayed when a Swing applet is running?

Wrap Up

Due Next:
Course Project (5/27/09)
Work on your project!
Home | Blackboard | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links
Last Updated: May 17 2009 @20:54:21