Wednesday, July 3, 2013

Events Examples

package com.spconger.EventExamples;
import acm.graphics.*;
import acm.program.*;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

public class Program  extends GraphicsProgram{
 /**
  * This program moves a turtle around using
  * two different events: KeyEvent and MouseEvent
  * July, 3 2013
  */

 //declare our turtle
 private GTurtle bob;
 //set constants for form width
 private final int FORMWIDTH=400;
 private final int FORMHEIGHT=600;

 public void run(){
  //set form size
  setSize(FORMWIDTH,FORMHEIGHT);
  //place the turtle in the center of the screen
  bob = new GTurtle(FORMWIDTH/2, FORMHEIGHT/2);
  //add the turtle to the screen
  add(bob);
  //wait for a mouse click to start
  waitForClick();
  //add the key listener
  addKeyListeners();
  //add the mouse listener
  addMouseListeners();
 }

 public void keyPressed(KeyEvent e){
  //this method handles the key event
  //we use a switch to determine
  //which keys to react to
  //for us just the arrow keys
  switch(e.getKeyCode()){
  case KeyEvent.VK_RIGHT:
   bob.setDirection(0);
   break;
  case KeyEvent.VK_LEFT:
   bob.setDirection(180);
   break;
  case KeyEvent.VK_UP:
   bob.setDirection(90);
   break;
  case KeyEvent.VK_DOWN:
   bob.setDirection(-90);
   break;
  default:
   return;

  }
  //move the turtle
  bob.forward(10);
 }

 public void mouseMoved(MouseEvent e){
  //get the mouse position
  Point movePos=e.getPoint();
  //get the x and y of the current mouse position
  int x = movePos.x;
  int y = movePos.y;
  //use them to set 
  bob.setLocation(x,y);

 }
}



No comments:

Post a Comment