Mouse Events and KeyboardEvents
Events are central to programming for a graphical user interface. The GUIprogram must be prepared to respond to various kinds of events that  canhappen at unpredictable times and in an order that the program doesn’tcontrol
The most basic kinds of events are generated by the mouse and keyboard.
In Java, events are represented by objects. Different types of events arerepresented by objects belonging to different classes.
For a mouse event, an object belonging to a class called MouseEvent isconstructed.
For a keyboard event, an object belonging to a class called KeyEvent isconstructed.
After the event object is constructed, it is passed as a parameter to a designatedsubroutine.
For a GUI program like Applet, although there is no main() routine there,there is still  a sort of main routine running somewhere that executes a loopto response the events. This loop is called an event loop. It’s part of “thesystem”.
“Listen” for the events
For an event to have any effect, a program must detect the event and reactto it.
Listening for events is done by an object called an event listener. Thisobject must contain instance methods for handling the events for which itlistens.
The methods that are required in a mouse event listener are specified in aninterface named MouseListerner.
An interface in Java is just a list of instance methods. A class can"implement" an interface by doing two things.
First, the class must be declared to implement the interface, as in "classMyListerner implements MouseListener" or "class RandomStrings extends Appletimplements MouseListener".
Second, the class must include a definition for each instance method specified inthe interface.
Every event in Java is associated with a GUI component. Before a listenerobject can “hear” events associated with a given component, the listenerobject must be registered with the component.
If you have a component object called comp, you can register in the followingway to listen the mouse event: comp.addMouseListener(Mylistener)
MouseEvent and MouseListener
The MouseListener interface specifies five different instancemethods:
1.public void mousePressed(MouseEvent evt);
2.public void mouseReleased(MouseEvent evt);
3.public void mouseClicked(MouseEvent evt);
4. public void mouseEntered(MouseEvent evt);
5.public void mouseExited(MouseEvent evt);
User can hold down certain modifier keys while using the mouse.The possible modifier keys include: the shift key, the control key,the ALT key. The boolean-valued instance methods can be usedare:
evt.isShiftDown(),
evt.isControlDown(),
evt.isAltDown()
evt.isMetaDown()
A MouseEvent example(SimpleStamper.java)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SimpleStamper extends Applet implementsMouseListener {
public void init() {
// When the applet is created, set its background color
// to black, and register the applet to listen to mouse
// events on itself.
setBackground(Color.black);
 addMouseListener(this);
}
public void mousePressed(MouseEvent evt) {
// This method will be called when the user clicks the
// mouse on the applet.
if ( evt.isShiftDown() ) {
// The user was holding down the Shift key. Just
// repaint the applet, which will fill it with its
// background color, black.
repaint();
return; }
int x = evt.getX(); // x-coordinate where user clicked.
int y = evt.getY(); // y-coordinate where user clicked.
Graphics g = getGraphics(); // Graphics context
// for drawing on the applet.
if ( evt.isMetaDown() ) { // User right-clicked at the point (x,y).
// Draw a blue oval centered at the point (x,y).
// A black outline around the oval will make it more
// distinct when ovals and rects overlap.
g.setColor(Color.blue);
g.fillOval( x - 25, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawOval( x - 25, y - 15, 60, 30 );
}
else { // Draw a red rectangle centered at the point (x,y).
g.setColor(Color.red);
g.fillRect( x - 25, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawRect( x - 25, y - 15, 60, 30 ); }
g.dispose();
// We are finished with the graphics context,
// so dispose of it.
} // end mousePressed()
// The following empty routines are required by the
// MouseListener interface:
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
} // end class SimpleStamper
What you need to notice from theprevious example
Put the import specification "importjava.awt.event.*;" at the beginning of yoursource code;
Declare that some class implements theappropriate listener interface, such asMouseListener;
Provide definitions in the class for thesubroutines from that interface;
Register the listener object with the applet orother component.
MouseMotionListeners andDragging
Whenever the mouse is moved, it generatesevents
The methods for responding to mouse motionevents are defined in interface namedMouseMotionListner. This interface specifiestwo event-handling methods:
public void mouseDragged(MouseEvent evt)
Mouse moving while a button on the mouse is pressed
public void mouseMoved(MouseEvent evt)
Mouse moving while no muse button is down
Example to listen the mouse moveevents
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Mouser extends Applet implementsMouseListener, MouseMotionListener {
public void init() { // set up the appletaddMouseListener(this);addMouseMotionListener(this);
 . . . // other initializations }
 . . // Define the seven MouseListener and .
// MouseMotionListener methods. Also, there .
// can be other variables and methods.
Keyboard Events
Keyboard event objects belong to a class calledKeyEvent.
The methods for responding to KeyEvent aredefined in interface named KeyListener. Thisinterface specifies three event-handlingmethods:
public void keyPressed(KeyEvent evt);
public void keyReleased(KeyEvent evt);
public void keyTyped(KeyEvent evt);
The KeyListener object must be registered witha component by calling the component’saddKeyListener() method.
Focus Events
In Java, objects are notified abut changes ofinput focus by events of type FocusEvent.
An object that wants to be notified of changes infocus can implement the FocusListenerinterface.
This interface declares two methods:
public void focusGained(FocusEvent evt);
public void focusLost(FocusEvent evt);
Example about KeyEvents and FousEvents (KeyboardAndFocusDemo.java)
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class KeyboardAndFocusDemo extends Applet
                  implements KeyListener, FocusListener, MouseListener {
 
   static final int SQUARE_SIZE = 40;  // Length of a side of the square.
   Color squareColor;  // The color of the square.
   int squareTop, squareLeft;  // Coordinates of top-left corner of square.
   boolean focussed = false;   // True when this applet has input focus.
 
   public void init() {
setBackground(Color.white);
      squareTop = getSize().height / 2 - SQUARE_SIZE / 2;
      squareLeft = getSize().width / 2 - SQUARE_SIZE / 2;
      squareColor = Color.red;
      addFocusListener(this);
      addKeyListener(this);
      addMouseListener(this);
   }
 
 public void paint(Graphics g) {
/* Draw a 3-pixel border, colored cyan if the applet has the  keyboard focus, or in lightgray if it does not. */
      if (focussed)
         g.setColor(Color.cyan);
      else
         g.setColor(Color.lightGray);
 
      int width = getSize().width;  // Width of the applet.
      int height = getSize().height; // Height of the applet.
      g.drawRect(0,0,width-1,height-1);
      g.drawRect(1,1,width-3,height-3);
      g.drawRect(2,2,width-5,height-5);
 
      /* Draw the square. */
      g.setColor(squareColor);
      g.fillRect(squareLeft, squareTop, SQUARE_SIZE, SQUARE_SIZE);
      /* If the applet does not have input focus, print a message. */
      if (!focussed) {
         g.setColor(Color.magenta);
         g.drawString("Click to activate",7,20);
      }
   }  // end paint()
 
 
   public void focusGained(FocusEvent evt) {
         // The applet now has the input focus.
      focussed = true;
      repaint();  // redraw with cyan border
   }
 
   public void focusLost(FocusEvent evt) {
         // The applet has now lost the input focus.
      focussed = false;
      repaint();  // redraw without cyan border
   }
 
 public void keyTyped(KeyEvent evt) {
     char ch = evt.getKeyChar();  // The character typed.
      if (ch == 'B' || ch == 'b') {
         squareColor = Color.blue;
         repaint();
      } else if (ch == 'G' || ch == 'g') {
         squareColor = Color.green;
         repaint();
      } else if (ch == 'R' || ch == 'r') {
         squareColor = Color.red;
         repaint();
      } else if (ch == 'K' || ch == 'k') {
         squareColor = Color.black;
         repaint();
      }
   }  // end keyTyped()
 
 public void keyPressed(KeyEvent evt) {
          // Called when the user has pressed a key, which can be
          // a special key such as an arrow key.  If the key pressed
          // was one of the arrow keys, move the square (but make sure
          // that it doesn't move off the edge, allowing for a
          // 3-pixel border all around the applet).
 
      int key = evt.getKeyCode();  // keyboard code for the key that was pressed
 
      if (key == KeyEvent.VK_LEFT) {
         squareLeft -= 8;
         if (squareLeft < 3)
            squareLeft = 3;
         repaint();
      }
      else if (key == KeyEvent.VK_RIGHT) {
         squareLeft += 8;
         if (squareLeft > getSize().width - 3 - SQUARE_SIZE)
            squareLeft = getSize().width - 3 - SQUARE_SIZE;
         repaint();
      }
      else if (key == KeyEvent.VK_UP) {
         squareTop -= 8;
         if (squareTop < 3)
            squareTop = 3;
         repaint();
      }
      else if (key == KeyEvent.VK_DOWN) {
         squareTop += 8;
         if (squareTop > getSize().height - 3 - SQUARE_SIZE)
            squareTop = getSize().height - 3 - SQUARE_SIZE;
         repaint();
      }
   }  // end keyPressed()
 public void keyReleased(KeyEvent evt) {
      // empty method, required by the KeyListener Interface
   }
 
   public void mousePressed(MouseEvent evt) {
        // Request the input focus when the user clicks on the applet.
requestFocus();
   }
 
 
   public void mouseEntered(MouseEvent evt) { }  // Required by the
   public void mouseExited(MouseEvent evt) { }   //    MouseListener
   public void mouseReleased(MouseEvent evt) { } //       interface.
   public void mouseClicked(MouseEvent evt) { }
} // end class KeyboardAndFocusDemo