Event Handling

Laying out the graphical components of the program can be enough of a challenge, but handling the events that are generated by those components involves the meat and potatoes programming for any useful application.

This applet shows how to catch a "mouse down" event. The mouseDown() method of the applet is overridden to catch and handle any mouse clicks that take place within the applet. Clicking within the applet causes a second button to be alternately added and removed from the display.

  public boolean mouseDown(Event evt, int x, int y) {

  // If the second button is present then remove it.
  // Otherwise add it.

   if (second_button_present) {
    remove(button2);
    second_button_present = false;
   }
   else {
    button2 = new Button("Button #2");
    add(button2);
    second_button_present = true;
   }

  // Layout and repaint all of the components in the applet.

   layout();
   repaint();

   return true;

  }

Source code.

All of the event handling methods are defined in the Component Class. Some of the methods associated with event handling are:

action(Event evt, Object, obj) Handles events generated by Button presses, Item selections, and Text Entering.
handleEvent(Event evt) Handles all events. This is the most general purpose method.
keyDown(Event evt, int key) Handles events generated by pressing a key on the keyboard.
keyUp(Event evt, int key) Handles events generated by releasing a depressed key.
mouseDown(Event evt, int x, int y) Handles events generated by pressing the mouse button.
mouseUp(Event evt, int x, int y) Handles events generated by releasing the mouse button.
mouseDrag(Event evt, int x int y) Handles events generated by moving the mouse while the mouse button is depressed.
mouseEnter(Event evt, int x, int y) Handles events generated when the cursor enters the component.
mouseExit(Event evt, int x, int y) Handles events generated when the cursor exits the component.

next page...


Last updated March 20, 1997 / ratliff@Princeton.EDU