Kladdy

Untitled

Jan 15th, 2014
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. import java.applet.Applet;
  2. import java.awt.Graphics;
  3. import java.awt.Graphics2D;
  4. import java.awt.Rectangle;
  5. import java.awt.event.KeyEvent;
  6. import java.awt.event.KeyListener;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10.  
  11. public class KeyListenerTutorial
  12. extends Applet
  13. implements KeyListener{
  14.    
  15.     private Rectangle rect;
  16.    
  17.     private ArrayList<Integer> keysDown;
  18.    
  19.     public void init()
  20.     {
  21.         this.addKeyListener(this);
  22.        
  23.         keysDown = new ArrayList<Integer>();
  24.         rect = new Rectangle(0, 0, 50, 50);
  25.     }
  26.    
  27.     public void paint(Graphics g)
  28.     {
  29.         setSize(500, 500);
  30.         Graphics2D g2 = (Graphics2D)g;
  31.        
  32.         g2.fill(rect);
  33.     }
  34.  
  35.     @Override
  36.     public void keyPressed(KeyEvent e) {
  37.         if (!keysDown.contains(e.getKeyCode()))
  38.             keysDown.add(new Integer(e.getKeyCode()));
  39.        
  40.         moveRect();
  41.        
  42.         /*
  43.         if (e.getKeyCode() == KeyEvent.VK_RIGHT)
  44.         {
  45.             rect.setLocation(rect.x + 2, rect.y);
  46.         }
  47.          if (e.getKeyCode() == KeyEvent.VK_LEFT)
  48.         {
  49.             rect.setLocation(rect.x - 2, rect.y);
  50.         }
  51.          if (e.getKeyCode() == KeyEvent.VK_UP)
  52.         {
  53.             rect.setLocation(rect.x, rect.y - 2);
  54.         }
  55.          if (e.getKeyCode() == KeyEvent.VK_DOWN)
  56.         {
  57.             rect.setLocation(rect.x, rect.y + 2);
  58.         }
  59. */
  60.        
  61.        
  62.     }
  63.  
  64.     @Override
  65.     public void keyReleased(KeyEvent e) {
  66.         keysDown.remove(new Integer(e.getKeyCode()));
  67.        
  68.        
  69.        
  70.     }
  71.    
  72.     public void moveRect()
  73.     {
  74.         int x = rect.x;
  75.         int y = rect.y;
  76.        
  77.         if (keysDown.contains(KeyEvent.VK_UP))
  78.             y -= 2;
  79.        
  80.         if (keysDown.contains(KeyEvent.VK_DOWN))
  81.             y += 2;
  82.        
  83.         if (keysDown.contains(KeyEvent.VK_LEFT))
  84.             x -= 2;
  85.        
  86.         if (keysDown.contains(KeyEvent.VK_RIGHT))
  87.             x += 2;
  88.        
  89.         rect.setLocation(x,y);
  90.        
  91.         repaint();
  92.    
  93.        
  94.     }
  95.  
  96.     @Override
  97.     public void keyTyped(KeyEvent e) {
  98.        
  99.        
  100.     }
  101.    
  102.    
  103.  
  104. }
Advertisement
Add Comment
Please, Sign In to add comment