CS 4773 Object Oriented Systems Event Handling in Java


Topics: Event Handling Buttons
We will describe only the simplest examples here.
Look at the example button code.

Key Events
To capture key events, set a KeyListener which implements:

   public void keyPressed(KeyEvent e);
   public void keyReleased(KeyEvent e);
   public void keyTyped(KeyEvent e);
You must also execute:
setFocusable(true);
Setting the focus was more difficult before JDK 1.4.

Mouse Events
There are two groups of mouse events: MouseEvent and MouseMotionEvent.

You can add a listener to any Component, e.g.

    JPanel jp = new JPanel();
    jp.addMouseLisener(xxx);
    jp.addMouseMotionListener(xxx);
A MouseListener must implement:
   public void mouseClicked(MouseEvent e);
   public void mouseEntered(MouseEvent e);
   public void mouseExited(MouseEvent e);
   public void mousePressed(MouseEvent e);
   public void mouseReleased(MouseEvent e);
Often you only need one of these, say mousePressed.
You still need to implement all of these and put an empty body in for each.
See the Mouse1 example.

Alternatively, you can just extend mouseAdapter which is a class that has these 5 functions with empty bodies. Just override the ones you want to use.

This alone is not useful since a class can extend only one other class

This is weher inner classes come in.
Make an inner class that extends mouseAdpater can override just the mousePressed method. The inner class has access to all of the private methods of its outer class.
See the Mouse2 example.

The MouseMotionListener must implement:

   public void mouseMoved(MouseEvent e);
   public void mouseDragged(MouseEvent e);

The MouseInputListener (part of swing, not awt) is a third kind of mouse listener that combines the two.
See the Mouse3 example.