Saturday 25 March 2017

Creating a Frame Window in an Applet - Java Tutorials

While it is possible to simply create a window by creating an instance of Frame, you will seldom do so, because you will not be able to do much with it. For example, you will not be able to receive or process events that occur within it or easily output information to it. Most of the time, you will create a subclass of Frame. Doing so lets you override Frame’s methods and event handling.

Creating a new frame window from within an applet is actually quite easy. First, create a subclass of Frame. Next, override any of the standard window methods, such as init( ), start( ), stop( ), and paint( ). Finally, implement the windowClosing( ) method of the WindowListener interface, calling setVisible(false) when the window is closed.

Once you have defined a Frame subclass, you can create an object of that class. This causes a frame window to come into existence, but it will not be initially visible. You make it visible by calling setVisible( ). When created, the window is given a default height and width. You can set the size of the window explicitly by calling the setSize( ) method.

The following applet creates a subclass of Frame called SampleFrame. A window of this subclass is instantiated within the init( ) method of AppletFrame. Notice that SampleFrame calls Frame’s constructor. This causes a standard frame window to be created with the title passed in title. This example overrides the applet window’s start( ) and stop( ) methods so that they show and hide the child window, respectively. This causes the window to be removed automatically when you terminate the applet, when you close the window, or, if using a browser, when you move to another page. It also causes the child window to be shown when the browser returns to the applet.

  // Create a child frame window from within an applet.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="AppletFrame" width=300 height=50>
    </applet>
  */

  // Create a subclass of Frame.
  class SampleFrame extends Frame {
    SampleFrame(String title) {
      super(title);
      // create an object to handle window events
      MyWindowAdapter adapter = new MyWindowAdapter(this);
        // register it to receive those events
        addWindowListener(adapter);
    }

    public void paint(Graphics g) {
      g.drawString("This is in frame window", 10, 40);
    }
  }

  class MyWindowAdapter extends WindowAdapter {
    SampleFrame sampleFrame;
    public MyWindowAdapter(SampleFrame sampleFrame) {
      this.sampleFrame = sampleFrame;
    }
    public void windowClosing(WindowEvent we) {
      sampleFrame.setVisible(false);
    }
  }

  // Create frame window.
  public class AppletFrame extends Applet {
    Frame f;
    public void init() {
      f = new SampleFrame("A Frame Window");

      f.setSize(250, 250);
      f.setVisible(true);
    }
    public void start() {
      f.setVisible(true);
    }
    public void stop() {
      f.setVisible(false);
    }
    public void paint(Graphics g) {
      g.drawString("This is in applet window", 10, 20);
    }
  }


Handling Events in a Frame Window

Since Frame is a subclass of Component, it inherits all the capabilities defined by Component. This means that you can use and manage a frame window that you create just like you manage your applet’s main window. For example, you can override paint( ) to display output, call repaint( ) when you need to restore the window, and override all event handlers. Whenever an event occurs in a window, the event handlers defined by that window will be called. Each window handles its own events. For example, the following program creates a window that responds to mouse events. The main applet window also responds to mouse events. When you experiment with this program, you will see that mouse events are sent to the window in which the event occurs.

  // Handle mouse events in both child and applet windows.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="WindowEvents" width=300 height=50>
    </applet>
  */

  // Create a subclass of Frame.
  class SampleFrame extends Frame
    implements MouseListener, MouseMotionListener {

    String msg = "";
    int mouseX=10, mouseY=40;
    int movX=0, movY=0;

    SampleFrame(String title) {
      super(title);
      // register this object to receive its own mouse events
      addMouseListener(this);
      addMouseMotionListener(this);
      // create an object to handle window events
      MyWindowAdapter adapter = new MyWindowAdapter(this);
      // register it to receive those events
      addWindowListener(adapter);
    }

    // Handle mouse clicked.
    public void mouseClicked(MouseEvent me) {
    }

    // Handle mouse entered.
    public void mouseEntered(MouseEvent evtObj) {
      // save coordinates
      mouseX = 10;
      mouseY = 54;
      msg = "Mouse just entered child.";
      repaint();
    }

    // Handle mouse exited.
    public void mouseExited(MouseEvent evtObj) {
      // save coordinates
      mouseX = 10;
      mouseY = 54;
      msg = "Mouse just left child window.";
      repaint();
    }
   
    // Handle mouse pressed.
    public void mousePressed(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Down";
      repaint();
    }
    // Handle mouse released.
    public void mouseReleased(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Up";
      repaint();
    }

    // Handle mouse dragged.
    public void mouseDragged(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      movX = me.getX();
      movY = me.getY();
      msg = "*";
      repaint();
    }

    // Handle mouse moved.
    public void mouseMoved(MouseEvent me) {
      // save coordinates
      movX = me.getX();
      movY = me.getY();
      repaint(0, 0, 100, 60);
    }

    public void paint(Graphics g) {
      g.drawString(msg, mouseX, mouseY);
      g.drawString("Mouse at " + movX + ", " + movY, 10, 40);
    }
  }

  class MyWindowAdapter extends WindowAdapter {
    SampleFrame sampleFrame;
    public MyWindowAdapter(SampleFrame sampleFrame) {
      this.sampleFrame = sampleFrame;
    }

    public void windowClosing(WindowEvent we) {
      sampleFrame.setVisible(false);
    }
  }

  // Applet window.
  public class WindowEvents extends Applet
    implements MouseListener, MouseMotionListener {

    SampleFrame f;
    String msg = "";
    int mouseX=0, mouseY=10;
    int movX=0, movY=0;

    // Create a frame window.
    public void init() {
      f = new SampleFrame("Handle Mouse Events");
      f.setSize(300, 200);
      f.setVisible(true);

      // register this object to receive its own mouse events
      addMouseListener(this);
      addMouseMotionListener(this);
    }

    // Remove frame window when stopping applet.
    public void stop() {
      f.setVisible(false);
    }

    // Show frame window when starting applet.
    public void start() {
      f.setVisible(true);
    }

    // Handle mouse clicked.
    public void mouseClicked(MouseEvent me) {
    }

    // Handle mouse entered.
    public void mouseEntered(MouseEvent me) {
      // save coordinates
      mouseX = 0;
      mouseY = 24;
      msg = "Mouse just entered applet window.";
      repaint();
    }

    // Handle mouse exited.
    public void mouseExited(MouseEvent me) {
      // save coordinates
      mouseX = 0;
      mouseY = 24;
      msg = "Mouse just left applet window.";
      repaint();
    }

    // Handle button pressed.
    public void mousePressed(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Down";
      repaint();
    }

    // Handle button released.
    public void mouseReleased(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Up";
      repaint();
    }

    // Handle mouse dragged.
    public void mouseDragged(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      movX = me.getX();
      movY = me.getY();
      msg = "*";
      repaint();
    }

    // Handle mouse moved.
    public void mouseMoved(MouseEvent me) {
      // save coordinates
      movX = me.getX();
      movY = me.getY();
      repaint(0, 0, 100, 20);
    }

    // Display msg in applet window.
    public void paint(Graphics g) {
      g.drawString(msg, mouseX, mouseY);
      g.drawString("Mouse at " + movX + ", " + movY, 0, 10);
    }
  }

AWT Classes, Window Fundamentals & Working with Frame Windows - Java Tutorials

AWT Classes

The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. Fortunately, because it is logically organized in a top-down, hierarchical fashion, it is easier to understand and use than you might at first believe. lists some of the many AWT classes.


Some AWT Classes

AWTEvent:  Encapsulates AWT events.

AWTEventMulticaster:  Dispatches events to multiple listeners.

BorderLayout:  The border layout manager. Border layouts use five components: North, South, East, West, and Center.

Button:  Creates a push button control.

Canvas:  A blank, semantics-free window.

CardLayout:  The card layout manager. Card layouts emulate index cards. Only the one on top is showing.

Checkbox:  Creates a check box control.

CheckboxGroup:  Creates a group of check box controls.

CheckboxMenuItem:  Creates an on/off menu item.

Choice:  Creates a pop-up list.

Color:  Manages colors in a portable, platform-independent fashion.

Component:  An abstract superclass for various AWT components.

Container:  A subclass of Component that can hold other components.

Cursor:  Encapsulates a bitmapped cursor.

Dialog:  Creates a dialog window.

Dimension:  Specifies the dimensions of an object. The width is stored in width, and the height is stored in height.

Event:  Encapsulates events.

EventQueue:  Queues events.

FileDialog:  Creates a window from which a file can be selected.

FlowLayout:  The flow layout manager. Flow layout positions components left to right, top to bottom.

Font:  Encapsulates a type font.

FontMetrics Encapsulates various information related to a font. This information helps you display text in a window.

Frame:  Creates a standard window that has a title bar, resize corners, and a menu bar.

Graphics:  Encapsulates the graphics context. This context is used by the various output methods to display output in a window.

GraphicsDevice:  Describes a graphics device such as a screen or printer.

GraphicsEnvironment:  Describes the collection of available Font and GraphicsDevice objects.

GridBagConstraints:  Defines various constraints relating to the GridBagLayout class.

GridBagLayout:  The grid bag layout manager. Grid bag layout displays components subject to the constraints specified by GridBagConstraints.

GridLayout:  The grid layout manager. Grid layout displays components in a two-dimensional grid.

Image:  Encapsulates graphical images.

Insets:  Encapsulates the borders of a container.

Label:  Creates a label that displays a string.

List:  Creates a list from which the user can choose. Similar to the standard Windows list box.

MediaTracker:  Manages media objects.

Menu:  Creates a pull-down menu.

MenuBar:  Creates a menu bar.

MenuComponent:  An abstract class implemented by various menu classes.

MenuItem:  Creates a menu item.

MenuShortcut Encapsulates a keyboard shortcut for a menu item.

Panel:  The simplest concrete subclass of Container.

Point:  Encapsulates a Cartesian coordinate pair, stored in x and y.

Polygon:  Encapsulates a polygon.

PopupMenu:  Encapsulates a pop-up menu.

PrintJob:  An abstract class that represents a print job.

Rectangle:  Encapsulates a rectangle.

Robot:  Supports automated testing of AWT- based applications. (Added by Java 2, vl.3)

Scrollbar:  Creates a scroll bar control.

ScrollPane:  A container that provides horizontal and/or vertical scroll bars for another component.

SystemColor:  Contains the colors of GUI widgets such as windows, scroll bars, text, and others.

TextArea:  Creates a multiline edit control.

TextComponent:  A superclass for TextArea and TextField.

TextField:  Creates a single-line edit control.

Toolkit:  Abstract class implemented by the AWT.

Window:  Creates a window with no frame, no menu bar, and no title.


Although the basic structure of the AWT has been the same since Java 1.0, some of the original methods were deprecated and replaced by new ones when Java 1.1 was released. For backward-compatibility, Java 2 still supports all the original 1.0 methods. However, because these methods are not for use with new code, this book does not describe them.




Window Fundamentals

The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window. Much of the functionality of these windows is derived from their parent classes. Thus, a description of the class hierarchies relating to these two classes is fundamental to their understanding.


Component

At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting.  A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.


Container

The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains. It does this through the use of various layout managers.


Panel

The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. When you run an applet using an applet viewer, the applet viewer provides the title and border.

Other components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component.


Window

The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame, described next.


Frame

Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window,” to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer. (An applet that could masquerade as a host-based application could be used to obtain passwords and other sensitive information without the user’s knowledge.) When a Frame window is created by a program rather than an applet, a normal window is created.


Canvas

Although it is not part of the hierarchy for applet or frame windows, there is one other type of window that you will find valuable: Canvas. Canvas encapsulates a blank window upon which you can draw. You will see an example of Canvas later in this book.




Working with Frame Windows

After the applet, the type of window you will most often create is derived from Frame. You will use it to create child windows within applets, and top-level or child windows for applications. As mentioned, it creates a standard-style window.

Here are two of Frame’s constructors:

      Frame( )
      Frame(String title)

The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Notice that you cannot specify the dimensions of the window. Instead, you must set the size of the window after it has been created. There are several methods you will use when working with Frame windows. They are examined here.


Setting the Window’s Dimensions

The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:

      void setSize(int newWidth, int newHeight)
      void setSize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels. The getSize( ) method is used to obtain the current size of a window. Its signature is shown here:

      Dimension getSize( )

This method returns the current size of the window contained within the width and height fields of a Dimension object.


Hiding and Showing a Window

After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is shown here:

      void setVisible(boolean visibleFlag)

The component is visible if the argument to this method is true. Otherwise, it is hidden.


Setting a Window’s Title

You can change the title in a frame window using setTitle( ), which has this general form:

      void setTitle(String newTitle)

Here, newTitle is the new title for the window.


Closing a Frame Window

When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the WindowListener interface. Inside windowClosing( ), you must remove the window from the screen. The example in the next section illustrates this technique.

Adapter Classes & Inner Classes - Java Tutorials

Adapter Classes

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.

For example,  the MouseMotionAdapter class has two methods, mouseDragged( ) and  mouseMoved ( ). The signatures of these empty methods are exactly as defined in the MouseMotionListener interface. If you were interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged( ). The empty implementation of mouseMoved ( ) would handle the mouse motion events for you. Lists the commonly used adapter classes in java.awt.event and notes the interface that each implements.

The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored. The program has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of MyMouseAdapter and registers that object to receive notifications of mouse events. It also creates an instance of MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of the constructors take a reference to the applet as an argument.

MyMouseAdapter implements the mouseClicked( ) method. The other mouse events are silently ignored by code inherited from the MouseAdapter class. MyMouseMotionAdapter implements the mouseDragged( ) method. The other mouse motion event is silently ignored by code inherited from the MouseMotionAdapter class.


Commonly Used Listener Interfaces Implemented by Adapter Classes

ComponentAdapter  --  ComponentListener

ContainerAdapter  --  ContainerListener

FocusAdapter  --  FocusListener

KeyAdapter  --  KeyListener

MouseAdapter  --  MouseListener

MouseMotionAdapter  --  MouseMotionListener

WindowAdapter  --  WindowListener


Note that both of our event listener classes save a reference to the applet. This information is provided as an argument to their constructors and is used later to invoke the showStatus( ) method.

  // Demonstrate an adapter.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="AdapterDemo" width=300 height=100>
    </applet>
  */

  public class AdapterDemo extends Applet {
    public void init() {
       addMouseListener(new MyMouseAdapter(this));
       addMouseMotionListener(new MyMouseMotionAdapter(this));
    }
  }

  class MyMouseAdapter extends MouseAdapter {

    AdapterDemo adapterDemo;
    public MyMouseAdapter(AdapterDemo adapterDemo) {
      this.adapterDemo = adapterDemo;
    }

    // Handle mouse clicked.
    public void mouseClicked(MouseEvent me) {
      adapterDemo.showStatus("Mouse clicked");
    }
  }
  
  class MyMouseMotionAdapter extends MouseMotionAdapter {
    AdapterDemo adapterDemo;
    public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
      this.adapterDemo = adapterDemo;
    }

    // Handle mouse dragged.
    public void mouseDragged(MouseEvent me) {
      adapterDemo.showStatus("Mouse dragged");
    }
  }

As you can see by looking at the program, not having to implement all of the methods defined by the MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort and prevents your code from becoming cluttered with empty methods. As an exercise, you might want to try rewriting one of the keyboard input examples shown earlier so that it uses a KeyAdapter.




Inner Classes

In Chapter 7, the basics of inner classes were explained. Here you will see why they are important. Recall that an inner class is a class defined within other class, or even within an expression. This section illustrates how inner classes can be used to simplify the code when using event adapter classes.

To understand the benefit provided by inner classes, consider the applet shown in the following listing. It does not use an inner class. Its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed. There are two top-level classes in this program. MousePressedDemo extends Applet, and MyMouseAdapter extends MouseAdapter. The init( ) method of MousePressedDemo instantiates MyMouseAdapter and provides this object as an argument to the addMouseListener( ) method.

Notice that a reference to the applet is supplied as an argument to the MyMouseAdapter constructor. This reference is stored in an instance variable for later use by the mousePressed( ) method. When the mouse is pressed, it invokes the showStatus( ) method of the applet through the stored applet reference. In other words, showStatus( ) is invoked relative to the applet reference stored by MyMouseAdapter.

  // This applet does NOT use an inner class.
  import java.applet.*;
  import java.awt.event.*;
  /*
    <applet code="MousePressedDemo" width=200 height=100>
    </applet>
  */

  public class MousePressedDemo extends Applet {
    public void init() {
      addMouseListener(new MyMouseAdapter(this));
    }
  }

  class MyMouseAdapter extends MouseAdapter {
    MousePressedDemo mousePressedDemo;
    public MyMouseAdapter(MousePressedDemo mousePressedDemo) {
      this.mousePressedDemo = mousePressedDemo;
    }

    public void mousePressed(MouseEvent me) {
      mousePressedDemo.showStatus("Mouse Pressed.");
    }
  }

The following listing shows how the preceding program can be improved by using an inner class. Here, InnerClassDemo is a top-level class that extends Applet. MyMouseAdapter is an inner class that extends MouseAdapter. Because MyMouseAdapter is defined within the scope of InnerClassDemo, it has access to all of the variables and methods within the scope of that class. Therefore, the mousePressed( ) method can call the showStatus( ) method directly. It no longer needs to do this via a stored reference to the applet. Thus, it is no longer necessary to pass MyMouseAdapter( ) a reference to the invoking object.

  // Inner class demo.
  import java.applet.*;
  import java.awt.event.*;
  /*
    <applet code="InnerClassDemo" width=200 height=100>
    </applet>
  */

  public class InnerClassDemo extends Applet {
    public void init() {
      addMouseListener(new MyMouseAdapter());
    }
    class MyMouseAdapter extends MouseAdapter {
      public void mousePressed(MouseEvent me) {
        showStatus("Mouse Pressed");
      }
    }
  }


Anonymous Inner Classes

An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner class can facilitate the writing of event handlers. Consider the applet shown in the following listing. As before, its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed.

  // Anonymous inner class demo.
  import java.applet.*;
  import java.awt.event.*;
  /*
    <applet code="AnonymousInnerClassDemo" width=200 height=100>
    </applet>
  */

  public class AnonymousInnerClassDemo extends Applet {
    public void init() {
      addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
          showStatus("Mouse Pressed");
        }
      });
    }
  }

There is one top-level class in this program: AnonymousInnerClassDemo. The init( ) method calls the addMouseListener( ) method. Its argument is an expression that defines and instantiates an anonymous inner class. Let’s analyze this expression carefully.

The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the braces defines an anonymous inner class. Furthermore, that class extends MouseAdapter. This new class is not named, but it is automatically instantiated when this expression is executed.

Because this anonymous inner class is defined within the scope of AnonymousInnerClassDemo, it has access to all of the variables and methods within the scope of that class. Therefore, it can call the showStatus( ) method directly. As just illustrated, both named and anonymous inner classes solve some annoying problems in a simple yet effective way. They also allow you to create more efficient code.

Using the Delegation Event Model - Java Tutorials

Now that you have learned the theory behind the delegation event model and have had an overview of its various components, it is time to see it in practice. Applet programming using the delegation event model is actually quite easy. Just follow these two steps:

  1. Implement the appropriate interface in the listener so that it will receive the type of event desired.
  2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.

Remember that a source may generate several types of events. Each event must be registered separately. Also, an object may register to receive several types of events, but it must implement all of the interfaces that are required to receive these events. To see how the delegation model works in practice, we will look at examples that handle the two most commonly used event generators: the mouse and keyboard.


Handling Mouse Events

To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. (You may also want to implement MouseWheelListener, but we won’t be doing so, here.) The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the upper-left corner of the applet display area.

As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used by paint( ) to display output at the point of these occurrences.

  // Demonstrate the mouse event handlers.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
  <applet code="MouseEvents" width=300 height=100>
  </applet>
  */

  public class MouseEvents extends Applet
    implements MouseListener, MouseMotionListener {

    String msg = "";
    int mouseX = 0, mouseY = 0; // coordinates of mouse

    public void init() {
       addMouseListener(this);
       addMouseMotionListener(this);
    }

    // Handle mouse clicked.
    public void mouseClicked(MouseEvent me) {
      // save coordinates
      mouseX = 0;
      mouseY = 10;
      msg = "Mouse clicked.";
      repaint();
    }

    // Handle mouse entered.
    public void mouseEntered(MouseEvent me) {
      // save coordinates
      mouseX = 0;
      mouseY = 10;
      msg = "Mouse entered.";
      repaint();
    }

    // Handle mouse exited.
    public void mouseExited(MouseEvent me) {
      // save coordinates
      mouseX = 0;
      mouseY = 10;
      msg = "Mouse exited.";
      repaint();
    }

    // Handle button pressed.
    public void mousePressed(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Down";
      repaint();
    }

    // Handle button released.
    public void mouseReleased(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "Up";
      repaint();
    }

    // Handle mouse dragged.
    public void mouseDragged(MouseEvent me) {
      // save coordinates
      mouseX = me.getX();
      mouseY = me.getY();
      msg = "*";
      showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
      repaint();
    }

    // Handle mouse moved.
    public void mouseMoved(MouseEvent me) {
      // show status
      showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
    }

    // Display msg in applet window at current X,Y location.
    public void paint(Graphics g) {
      g.drawString(msg, mouseX, mouseY);
    }
  }

Let’s look closely at this example. The MouseEvents class extends Applet and implements both the MouseListener and MouseMotionListener interfaces. These two interfaces contain methods that receive and process the various types of mouse events. Notice that the applet is both the source and the listener for these events. This works because Component, which supplies the addMouseListener( ) and addMouseMotionListener( ) methods, is a superclass of Applet. Being both the source and the listener for events is a common situation for applets.

Inside init( ), the applet registers itself as a listener for mouse events. This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are members of Component. They are shown here:

      void addMouseListener(MouseListener ml)
      void addMouseMotionListener(MouseMotionListener mml)

Here, ml is a reference to the object receiving mouse events, and mml is a reference to the object receiving mouse motion events. In this program, the same object is used for both. The applet then implements all of the methods defined by the MouseListener and MouseMotionListener interfaces. These are the event handlers for the various mouse events. Each method handles its event and then returns.


Handling Keyboard Events

To handle keyboard events, you use the same general architecture as that shown in the mouse event example in the preceding section. The difference, of course, is that you will be implementing the KeyListener interface.

Before looking at an example, it is useful to review how key events are generated. When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the user presses a key, at least two and often three events are generated. If all you care about are actual characters, then you can ignore the information passed by the key press and release events. However, if your program needs to handle special keys, such as the arrow or function keys, then it must watch for them through the  keyPressed ( ) handler.

There is one other requirement that your program must meet before it can process keyboard events: it must request input focus. To do this, call requestFocus( ), which is defined by Component. If you don’t, then your program will not receive any keyboard events. The following program demonstrates keyboard input. It echoes keystrokes to the applet window and shows the pressed/released status of each key in the status window.

  // Demonstrate the key event handlers.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="SimpleKey" width=300 height=100>
    </applet>
  */

  public class SimpleKey extends Applet
    implements KeyListener {

    String msg = "";
    int X = 10, Y = 20; // output coordinates

    public void init() {
      addKeyListener(this);
      requestFocus(); // request input focus
    }

    public void keyPressed(KeyEvent ke) {
      showStatus("Key Down");
    }

    public void keyReleased(KeyEvent ke) {
      showStatus("Key Up");
    }

    public void keyTyped(KeyEvent ke) {
      msg += ke.getKeyChar();
      repaint();
    }

    // Display keystrokes.
    public void paint(Graphics g) {
      g.drawString(msg, X, Y);
    }
  }

If you want to handle the special keys, such as the arrow or function keys, you need to respond to them within the keyPressed( ) handler. They are not available through keyTyped( ). To identify the keys, you use their virtual key codes. For example, the next applet outputs the name of a few of the special keys:

  // Demonstrate some virtual key codes.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="KeyEvents" width=300 height=100>
    </applet>
  */

  public class KeyEvents extends Applet
    implements KeyListener {

    String msg = "";
    int X = 10, Y = 20; // output coordinates

    public void init() {
      addKeyListener(this);
      requestFocus(); // request input focus
    }

    public void keyPressed(KeyEvent ke) {
      showStatus("Key Down");
      
      int key = ke.getKeyCode();
      switch(key) {
        case KeyEvent.VK_F1:
          msg += "<F1>";
          break;
        case KeyEvent.VK_F2:
          msg += "<F2>";
          break;
        case KeyEvent.VK_F3:
          msg += "<F3>";
          break;
        case KeyEvent.VK_PAGE_DOWN:
          msg += "<PgDn>";
          break;
        case KeyEvent.VK_PAGE_UP:
          msg += "<PgUp>";
          break;
        case KeyEvent.VK_LEFT:
          msg += "<Left Arrow>";
          break;
        case KeyEvent.VK_RIGHT:
          msg += "<Right Arrow>";
          break;
      }

      repaint();
    }

    public void keyReleased(KeyEvent ke) {
      showStatus("Key Up");
    }

    public void keyTyped(KeyEvent ke) {
      msg += ke.getKeyChar();
      repaint();
    }

    // Display keystrokes.
    public void paint(Graphics g) {
      g.drawString(msg, X, Y);
    }
  }

The procedures shown in the preceding keyboard and mouse event examples can be generalized to any type of event handling, including those events generated by controls. In later chapters, you will see many examples that handle other types of events, but they will all follow the same basic structure as the programs just described.