Computer Graphics

Lecture 8c - Mouse and Keyboard Events

What are Events?


Interfaces


(a) in defining an interface the key word interface is used instead of the keyword abstract
(b) none of the methods in an interface are defined, only signatures are included.

public class sample extends example implements interface1{

}
 

Event Listener Interfaces


All the interfaces and the methods in them.
 

Event

Generated by

Listener Interface

Methods in them

Action event

Pressing a button

ActionListener

actionPerformed()

Adjustment event

Scroll bar is manipulated

AdjustmentListener

adjustmentValueChanged()

Component event

A component is hidden, moved, resized, or shown

ComponentListener

componentHidden() 
componentMoved()  componentResized() 
componentShown()

Container event

A component is added or removed from a container

ContainerListener

componentAdded() 
componentRemoved()

Focus event

A component gains or loses focus

FocusListener

focusGained() 
focusLost()

Item event

An item is selected or deselected

ItemListener

itemStateChanged()

Key event

A key is pressed, released or typed

KeyListener

keyPressed() 
keyReleased() 
keyTyped()

Mouse event

Mouse button is clicked, pressed or released.  Mouse pointer enters leaves a component

MouseListener

mouseClicked() 
mouseEntered() 
mouseExited() 
mousePressed() 
mouseReleased()

Mouse event

Mouse pointer is dragged or moved

MouseMotionListener

mouseDragged() 
mouseMoved()

Text event

Text value is changed

TextListener

textValueChanged()

Window event

A window is activated, closed, deactivated, deiconfied, opened, or quit

WindowListener

windowActivated() 
windowClosed() 
windowClosing() 
windowDeactivated() 
windowDeiconified() 
windowIconified() 
windowOpened()

Getting ready to handle events

Step 1: Import classes from the package:
 

import java.awt.event.*;

Step 2: Implement the appropriate listener interfaces.
 

public class sample extends Applet implements listenerinterface1{

} //Several listener interfaces can be listed, separated by commas.
 

Step 3: Register the listener object with the appropriate event source.
 

event_source_object.addevent_listenername(event_listener_object);
//Normally, you use the keyword this for event_listener_object.


Step 4: Define all the methods of the implemented listener interfaces. I

Mouse Events

 

Event Class

MouseEvent

Listener Interface

MouseListener

Listener Methods

public void mouseEntered(MouseEvent event) 
public void mouseExited(MouseEvent event) 
public void mouseClicked(MouseEvent event) 
public void mousePressed(MouseEvent event) 
public void mouseReleased(MouseEvent event) 

By looking at the name of the methods, it is clear which activity invokes which method. 

event.getX() returns (int) the x coordinate of mouse position. 
event.getY() returns (int) the y coordinate of mouse position. 
event.getClickCount() returns (int) the number of mouse clicks.

Four steps:

Step 1: Include the following import statement:
 

import java.awt.event.*;


Step 2: Include Implements MouseListener :
 

public class w2 extends Applet implements MouseListener {

}
 

Step 3: Register addMouseListener method in the applet.
 

this.addMouseListener (this);


Step 4: Define the five MouseListener methods:
 

public void mouseClicked(MouseEvent event){
}

public void mouseEntered(MouseEvent event){
}

public void mouseexited(MouseEvent event){
}

public void mousePressed(MouseEvent event){
}

public void mouseReleased(MouseEvent event){
}

 Example

The following program changes the applet background color, whenever the mouse event occurs.
 

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseEvent1 extends Applet implements MouseListener{

public void init() {

this.addMouseListener(this);

}

public void mouseClicked(MouseEvent e){

setBackground(Color.blue);

}

public void mouseEntered(MouseEvent e){

setBackground(Color.cyan);

}

public void mouseExited(MouseEvent e){

setBackground(Color.green);

}

public void mousePressed(MouseEvent e){

setBackground(Color.magenta);

}

public void mouseReleased(MouseEvent e){

setBackground(Color.yellow);

}

}

Mouse Motion Activities

 

Event Class

MouseEvent

Listener Interface

MouseMotionListener

Listener Methods

public void mouseMoved(MouseEvent event) 

Invoked when the mouse button has been moved on a component (with no buttons down).

public void mouseDragged(MouseEvent event)

Invoked when a mouse button is pressed on a component and then dragged.

event.getX() returns (int) the x coordinate of mouse position. 

event.getY() returns (int) the y coordinate of mouse position. 

event.getClickCount() returns (int) the number of mouse clicks.

 Example

The following program changes an applet’s background color when any mouse activity take place.
 

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseEvent2 extends Applet implements
MouseMotionListener,MouseListener{

public void init() {

this.addMouseListener(this);
this.addMouseMotionListener(this);

}

public void mouseMoved(MouseEvent event){

setBackground(Color.white);

}

public void mouseDragged(MouseEvent event){

setBackground(Color.black);

}

public void mouseClicked(MouseEvent e){

setBackground(Color.blue);

}

public void mouseEntered(MouseEvent e){

setBackground(Color.cyan);

}

public void mouseExited(MouseEvent e){

setBackground(Color.green);

}

public void mousePressed(MouseEvent e){

setBackground(Color.magenta);

}

public void mouseReleased(MouseEvent e){

setBackground(Color.yellow);

}

}
 


 

Example

The following program displays the coordinates of the mouse.
 

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseEvent3 extends Applet implements
MouseMotionListener,MouseListener{

public void init() {

this.addMouseListener(this);
this.addMouseMotionListener(this);

}

public void mouseMoved(MouseEvent event){

setBackground(Color.white);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mouseDragged(MouseEvent event){

setBackground(Color.black);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mouseClicked(MouseEvent event){

setBackground(Color.blue);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mouseEntered(MouseEvent event){

setBackground(Color.cyan);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mouseExited(MouseEvent event){

setBackground(Color.green);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mousePressed(MouseEvent event){

setBackground(Color.magenta);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void mouseReleased(MouseEvent event){

setBackground(Color.yellow);
int x = event.getX();
int y = event.getY();
print(x,y);

}

public void print(int x, int y){

showStatus("x coordinate is = "+x+" y coordinate is = "+y);

}

}

Example

The following program uses the coordinates of the mouse to draw circles.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
 

public class CircleDrawer2 extends Applet
                           implements MouseListener {
  private int radius = 25;

  public void init() {
    setForeground(Color.blue);
    addMouseListener(this);
  }

  // Remaining methods are from the MouseListener interface.

  public void mouseEntered(MouseEvent event) {}
  public void mouseExited(MouseEvent event) {}
  public void mouseReleased(MouseEvent event) {}
  public void mouseClicked(MouseEvent event) {}

  public void mousePressed(MouseEvent event) {
    Graphics g = getGraphics();
    g.fillOval(event.getX()-radius,
               event.getY()-radius,
               2*radius,
               2*radius);
  }
}
 
 
 


 

Example

Simple WhiteBoard

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

// An applet that lets you perform freehand drawing.
 

public class SimpleWhiteboard extends Applet {
  protected int lastX=0, lastY=0;

  public void init() {
    setBackground(Color.white);
    setForeground(Color.blue);
    addMouseListener(new PositionRecorder());
    addMouseMotionListener(new LineDrawer());
  }

  protected void record(int x, int y) {
    lastX = x;
    lastY = y;
  }

  // Record position that mouse entered window or
  // where user pressed mouse button.

  private class PositionRecorder extends MouseAdapter {
    public void mouseEntered(MouseEvent event) {
      requestFocus(); // Plan ahead for typing
      record(event.getX(), event.getY());
    }

    public void mousePressed(MouseEvent event) {
      record(event.getX(), event.getY());
    }
  }

  // As user drags mouse, connect subsequent positions
  // with short line segments.

  private class LineDrawer extends MouseMotionAdapter {
    public void mouseDragged(MouseEvent event) {
      int x = event.getX();
      int y = event.getY();
      Graphics g = getGraphics();
      g.drawLine(lastX, lastY, x, y);
      record(x, y);
    }
  }
}
 
 


 
 
 

Keyboard Events

  Whenever a key is pressed, an object of the KeyEvent class is generated.

Event Class

KeyEvent

Listener Interface

KeyListener

Listener Methods

public void keyPressed(KeyEvent event) 

Invoked when a key is pressed. 

public void keyReleased(KeyEvent event) 

Invoked when a key is released. 

public void keyTyped(KeyEvent event) 

Invoked when a key is typed (pressed and released).

KeyEvent class

For a list of Class variables (virtual key codes), which are defined as static and final, see Virtual Key Codes table below. 

event.getKeyChar() returns (char) the character pressed. 

event.getKeyCode() returns (int) the "virtual key code", see table below. 

event.getModifiers().

event.isShiftDown() returns (boolean) true if shift key is down. 

event.isControlDown() returns (boolean) true if control key is down. 

event.isAltDown() returns (boolean) true if alt key is down 

KeyEvent.getKeyModifiersText(int modifiers) returns (String).

KeyEvent.getKeyText(int keycode) returns (String).


 

Virtual Key Codes

Alpha keys

VK_A through VK_Z

Numeric keys

VK_0 through VK_9

Function keys

VK_F1 through VK_F12 

Action keys

VK_BACK_SPACE 

VK_ESCAPE, VK_PRINTSCREEN, VK_SCROLL_LOCK, VK_PAUSE 

Num pad number keys

VK_NUMPAD0 through VK_NUMPAD9

Other Num pad keys

VK_NUM_LOCK, VK_SLASH, VK_MULTIPLY, VK_SUBTRACT, VK_ADD, VK_HOME, VK_UP, VK_PAGE_UP, VK_LEFT, VK_RIGHT, VK_END, VK_DOWN, VK_PAGE_DOWN, VK_INSERT, VK_DELETE, VK_ENTER

Modifier keys

VK_ALT, VK_CAPS_LOCK, VK_CONTROL, VK_META, VK_SHIFT

Punctuation keys

VK_SPACE, VK_ENTER, VK_TAB, VK_BACK_QUOTE, VK_SLASH, VK_BACK_SLASH, VK_OPEN_BRACKET, VK_CLOSE_BRACKET, VK_PERIOD, VK_QUOTE, VK_SEMICOLON, VK_SEPARATOR, VK_COMMA, VK_DECIMAL, VK_EQUALS, 

Other keys

VK_ACCEPT, VK_CANCEL, VK_CLEAR, VK_CONVERT, VK_FINAL, VK_HELP, VK_KANA, VK_KANJI, VK_MODECHANGE, VK_NONCONVERT, VK_UNDEFINED, 

Note

if ( event.getKeyCode() == VK_A && KeyEvent.isShiftDown())
 


Example

The following program displays several text boxes.  Type any key in top box. The other boxes in the applet show information about the key pressed.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Keys1 extends Applet implements KeyListener{

TextField input;
TextField output1, output2, output3, output4, output5;
TextField output6, output7, output8;

public void init(){

input = new TextField(30);
input.addKeyListener(this);
output1 = new TextField(30);
output2 = new TextField(30);
output3 = new TextField(30);
output4 = new TextField(30);
output5 = new TextField(30);
output6 = new TextField(30);
output7 = new TextField(30);
output8 = new TextField(30);
add(input);
add(output1);
add(output2);
add(output3);
add(output4);
add(output5);
add(output6);
add(output7);
add(output8);

}

public void keyTyped(KeyEvent event){

}

public void keyPressed(KeyEvent event){

char char1 = event.getKeyChar();
int n = event.getKeyCode();
int modifiers = event.getModifiers();
output1.setText("You pressed "+char1);

output2.setText("Virtual key code value = "+n);
output3.setText("Name of key pressed = "+KeyEvent.getKeyText(n));
output4.setText("Shift was pressed = "+event.isShiftDown());
output5.setText("Control key down = "+event.isControlDown());
output6.setText("Alt key was pressed = "+event.isAltDown());
output7.setText("Modifiers value = "+event.getModifiers());
output8.setText("Modifier text

="+KeyEvent.getKeyModifiersText(modifiers));

}

public void keyReleased(KeyEvent event) {

}

}

Output


 

Example

The following program displays two boxes. Type each keyboard key in the first box and see result in the second box.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Keys2 extends Applet implements KeyListener{

TextField input;
TextField output;

public void init(){

input = new TextField(30);
input.addKeyListener(this);
output = new TextField(30);
add(input);
add(output);

}

public void keyTyped(KeyEvent event){

}

public void keyPressed(KeyEvent event){

String string = " ";

switch(event.getKeyCode()){

case KeyEvent.VK_ACCEPT: string = "You pressed VK_ACCEPT"; break;
case KeyEvent.VK_ADD: string = "You pressed VK_ADD"; break;
case KeyEvent.VK_ALT: string = "You pressed VK_ALT"; break;
case KeyEvent.VK_BACK_QUOTE: string = "You pressed VK_BACK_QUOTE"; break;
case KeyEvent.VK_BACK_SLASH: string = "You pressed VK_BACK_SLASH"; break;
case KeyEvent.VK_BACK_SPACE: string = "You pressed VK_BACK_SPACE"; break;
case KeyEvent.VK_CANCEL: string = "You pressed VK_CANCEL"; break;
case KeyEvent.VK_CAPS_LOCK: string = "You pressed VK_CAPS_LOCK"; break;
case KeyEvent.VK_CLEAR: string = "You pressed VK_CLEAR"; break;
case KeyEvent.VK_CLOSE_BRACKET: string = "You pressed VK_CLOSE_BRACKET"; break;
case KeyEvent.VK_COMMA: string = "You pressed VK_COMMA"; break;
case KeyEvent.VK_CONTROL: string = "You pressed VK_CONTROL"; break;
case KeyEvent.VK_CONVERT: string = "You pressed VK_CONVERT"; break;
case KeyEvent.VK_DECIMAL: string = "You pressed VK_DECIMAL"; break;
case KeyEvent.VK_DELETE: string = "You pressed VK_DELETE"; break;
case KeyEvent.VK_DIVIDE: string = "You pressed VK_DIVIDE"; break;
case KeyEvent.VK_DOWN: string = "You pressed VK_DOWN"; break;
case KeyEvent.VK_END: string = "You pressed VK_END"; break;
case KeyEvent.VK_ENTER: string = "You pressed VK_ENTER"; break;
case KeyEvent.VK_EQUALS: string = "You pressed VK_EQUALS"; break;
case KeyEvent.VK_ESCAPE: string = "You pressed VK_ESCAPE"; break;
case KeyEvent.VK_F1: string = "You pressed VK_F1"; break;
case KeyEvent.VK_F10: string = "You pressed VK_F10"; break;
case KeyEvent.VK_F11: string = "You pressed VK_F11"; break;
case KeyEvent.VK_F12: string = "You pressed VK_F12"; break;
case KeyEvent.VK_F2: string = "You pressed VK_F2"; break;
case KeyEvent.VK_F3: string = "You pressed VK_F3"; break;
case KeyEvent.VK_F4: string = "You pressed VK_F4"; break;
case KeyEvent.VK_F5: string = "You pressed VK_F5"; break;
case KeyEvent.VK_F6: string = "You pressed VK_F6"; break;
case KeyEvent.VK_F7: string = "You pressed VK_F7"; break;
case KeyEvent.VK_F8: string = "You pressed VK_F8"; break;
case KeyEvent.VK_F9: string = "You pressed VK_F9"; break;
case KeyEvent.VK_FINAL: string = "You pressed VK_FINAL"; break;
case KeyEvent.VK_HELP: string = "You pressed VK_HELP"; break;
case KeyEvent.VK_HOME: string = "You pressed VK_HOME"; break;
case KeyEvent.VK_INSERT: string = "You pressed VK_INSERT"; break;
case KeyEvent.VK_KANA: string = "You pressed VK_KANA"; break;
case KeyEvent.VK_KANJI: string = "You pressed VK_KANJI"; break;
case KeyEvent.VK_LEFT: string = "You pressed VK_LEFT"; break;
case KeyEvent.VK_META: string = "You pressed VK_META"; break;
case KeyEvent.VK_MODECHANGE: string = "You pressed VK_MODECHANGE"; break;
case KeyEvent.VK_MULTIPLY: string = "You pressed VK_MULTIPLY"; break;
case KeyEvent.VK_NONCONVERT: string = "You pressed VK_NONCONVERT"; break;
case KeyEvent.VK_NUM_LOCK: string = "You pressed VK_NUM_LOCK"; break;
case KeyEvent.VK_OPEN_BRACKET: string = "You pressed VK_OPEN_BRACKET"; break;
case KeyEvent.VK_PAGE_DOWN: string = "You pressed VK_PAGE_DOWN"; break;
case KeyEvent.VK_PAGE_UP: string = "You pressed VK_PAGE_UP"; break;
case KeyEvent.VK_PAUSE: string = "You pressed VK_PAUSE"; break;
case KeyEvent.VK_PERIOD: string = "You pressed VK_PERIOD"; break;
case KeyEvent.VK_PRINTSCREEN: string = "You pressed VK_PRINTSCREEN"; break;
case KeyEvent.VK_QUOTE: string = "You pressed VK_QUOTE"; break;
case KeyEvent.VK_RIGHT: string = "You pressed VK_RIGHT"; break;
case KeyEvent.VK_SCROLL_LOCK: string = "You pressed VK_SCROLL_LOCK"; break;
case KeyEvent.VK_SEMICOLON: string = "You pressed VK_SEMICOLON"; break;
case KeyEvent.VK_SEPARATER: string = "You pressed VK_SEPARATER"; break;
case KeyEvent.VK_SHIFT: string = "You pressed VK_SHIFT"; break;
case KeyEvent.VK_SLASH: string = "You pressed VK_SLASH"; break;
case KeyEvent.VK_SPACE: string = "You pressed VK_SPACE"; break;
case KeyEvent.VK_SUBTRACT: string = "You pressed VK_SUBTRACT"; break;
case KeyEvent.VK_TAB: string = "You pressed VK_TAB"; break;
case KeyEvent.VK_UNDEFINED: string = "You pressed VK_UNDEFINED"; break;
case KeyEvent.VK_UP: string = "Y0u pressed VK_UP"; break;
case KeyEvent.VK_A: string = "You pressed VK_A"; break;
case KeyEvent.VK_B: string = "You pressed VK_B"; break;
case KeyEvent.VK_C: string = "You pressed VK_C"; break;
case KeyEvent.VK_D: string = "You pressed VK_D"; break;
case KeyEvent.VK_E: string = "You pressed VK_E"; break;
case KeyEvent.VK_F: string = "You pressed VK_F"; break;
case KeyEvent.VK_G: string = "You pressed VK_G"; break;
case KeyEvent.VK_H: string = "You pressed VK_H"; break;
case KeyEvent.VK_I: string = "You pressed VK_I"; break;
case KeyEvent.VK_J: string = "You pressed VK_J"; break;
case KeyEvent.VK_K: string = "You pressed VK_K"; break;
case KeyEvent.VK_L: string = "You pressed VK_L"; break;
case KeyEvent.VK_M: string = "You pressed VK_M"; break;
case KeyEvent.VK_N: string = "You pressed VK_N"; break;
case KeyEvent.VK_O: string = "You pressed VK_O"; break;
case KeyEvent.VK_P: string = "You pressed VK_P"; break;
case KeyEvent.VK_Q: string = "You pressed VK_Q"; break;
case KeyEvent.VK_R: string = "You pressed VK_R"; break;
case KeyEvent.VK_S: string = "You pressed VK_S"; break;
case KeyEvent.VK_T: string = "You pressed VK_T"; break;
case KeyEvent.VK_U: string = "You pressed VK_U"; break;
case KeyEvent.VK_V: string = "You pressed VK_V"; break;
case KeyEvent.VK_W: string = "You pressed VK_W"; break;
case KeyEvent.VK_X: string = "You pressed VK_X"; break;
case KeyEvent.VK_Y: string = "You pressed VK_Y"; break;
case KeyEvent.VK_Z: string = "You pressed VK_Z"; break;
case KeyEvent.VK_0: string = "You pressed VK_0"; break;
case KeyEvent.VK_1: string = "You pressed VK_1"; break;
case KeyEvent.VK_2: string = "You pressed VK_2"; break;
case KeyEvent.VK_3: string = "You pressed VK_3"; break;
case KeyEvent.VK_4: string = "You pressed VK_4"; break;
case KeyEvent.VK_5: string = "You pressed VK_5"; break;
case KeyEvent.VK_6: string = "You pressed VK_6"; break;
case KeyEvent.VK_7: string = "You pressed VK_7"; break;
case KeyEvent.VK_8: string = "You pressed VK_8"; break;
case KeyEvent.VK_9: string = "You pressed VK_9"; break;
case KeyEvent.VK_NUMPAD0: string = "You pressed VK_NUMPAD0"; break;
case KeyEvent.VK_NUMPAD1: string = "You pressed VK_NUMPAD1"; break;
case KeyEvent.VK_NUMPAD2: string = "You pressed VK_NUMPAD2"; break;
case KeyEvent.VK_NUMPAD3: string = "You pressed VK_NUMPAD3"; break;
case KeyEvent.VK_NUMPAD4: string = "You pressed VK_NUMPAD4"; break;
case KeyEvent.VK_NUMPAD5: string = "You pressed VK_NUMPAD5"; break;
case KeyEvent.VK_NUMPAD6: string = "You pressed VK_NUMPAD6"; break;
case KeyEvent.VK_NUMPAD7: string = "You pressed VK_NUMPAD7"; break;
case KeyEvent.VK_NUMPAD8: string = "You pressed VK_NUMPAD8"; break;
case KeyEvent.VK_NUMPAD9: string = "You pressed VK_NUMPAD9"; break;
}

output.setText(string);

}

public void keyReleased(KeyEvent event) {

}

}

Output


 
 

Example

A better whiteboard that lets you enter text in addition to freehand drawing

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
 

public class Whiteboard extends SimpleWhiteboard {
  protected FontMetrics fm;

  public void init() {
    super.init();
    Font font = new Font("Serif", Font.BOLD, 20);
    setFont(font);
    fm = getFontMetrics(font);
    addKeyListener(new CharDrawer());
  }

  private class CharDrawer extends KeyAdapter {
    // When user types a printable character,
    // draw it and shift position rightwards.

    public void keyTyped(KeyEvent event) {
      String s = String.valueOf(event.getKeyChar());
      getGraphics().drawString(s, lastX, lastY);
      record(lastX + fm.stringWidth(s), lastY);
    }
  }
}
 

Output