Advertisement
rootUser

Move image/2d object (in applet)

Jul 9th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.70 KB | None | 0 0
  1. package game;
  2.  
  3. import java.awt.Graphics;
  4. import java.awt.KeyEventDispatcher;
  5. import java.awt.KeyboardFocusManager;
  6. import java.awt.event.KeyEvent;
  7.  
  8. import javax.swing.JApplet;
  9.  
  10. public class Gamer1 extends JApplet implements KeyEventDispatcher
  11. {
  12.     private int x = 50, y = 50;
  13.  
  14.     @Override
  15.     public void init()
  16.     {
  17.         KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
  18.     }
  19.  
  20.     @Override
  21.     public void paint(Graphics g) // will draw the background and the character
  22.     {
  23.         super.paint(g); // <- added to your code to clear the background
  24.         //         before re-painting the new square
  25.         g.fillRect(x, y, 20, 20);
  26.         g.fillRect(x, y, WIDTH, HEIGHT);
  27.  
  28.     }
  29.  
  30.     @Override
  31.     public boolean dispatchKeyEvent(KeyEvent e)
  32.     {
  33.         int keyCode = e.getKeyCode();
  34.  
  35.         switch( keyCode )
  36.         {
  37.         case KeyEvent.VK_UP:
  38.             if( y>0 )  //when up key is pressed and the position of the player is not on the edge
  39.             {
  40.                 y=y-19;
  41.                 repaint();
  42.             }
  43.             break;
  44.         case KeyEvent.VK_DOWN:
  45.             if( y<171 ) //when down key is pressed and the position of the player is not on the edge
  46.             {
  47.                 y=y+19;
  48.                 repaint();
  49.             }
  50.             break;
  51.         case KeyEvent.VK_LEFT:
  52.             if( x>0 )
  53.             {
  54.                 x=x-15;
  55.                 repaint();
  56.             }
  57.             break;
  58.         case KeyEvent.VK_RIGHT:
  59.             if( x<285 )
  60.             {
  61.                 x=x+15;
  62.                 repaint();
  63.             }
  64.             break;
  65.         }
  66.         return false;
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement