Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: How to get the arrow keys to move rectangle automatically

  1. #1
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default How to get the arrow keys to move rectangle automatically

    Hi everyone,

    I'm creating a snake game and I need some help getting the rectangle to move automatically when a arrow key is pressed by a user. I got it right now that it will move the amount in the x,y direction when an arrow key is pressed but then it stops. I want it to continuously move when an arrow key is pressed in that direction.

    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.Timer;
     
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import javax.swing.KeyStroke;
     
    /** 	 	 	 	 	 	
       This frame contains a moving rectangle.
    */
    public class RectangleFrame3 extends JFrame
    {
       private static final int FRAME_WIDTH = 300;
       private static final int FRAME_HEIGHT = 400;
       private int xLocation = 0;
     
       private RectangleComponent3 scene;
     
       class MousePressListener implements MouseListener
       {  
          public void mousePressed(MouseEvent event)
          {  
             int x = event.getX();
             int y = event.getY();
             scene.moveRectangleTo(x, y);
          }
     
          // Do-nothing methods
          public void mouseReleased(MouseEvent event) {}
          public void mouseClicked(MouseEvent event) {}
          public void mouseEntered(MouseEvent event) {}
          public void mouseExited(MouseEvent event) {}
       }
     
       class KeyStrokeListener implements KeyListener
       {
          public void keyPressed(KeyEvent event) 
          {
             String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (key.equals("DOWN"))
             {
                scene.moveRectangleBy(0, 5);            
             }
             else if (key.equals("UP"))
             {
                scene.moveRectangleBy(0, -5);            
             }
             else if (key.equals("LEFT"))
             {
                  scene.moveRectangleBy(-5, 0);
                //scene.moveRectangleBy(scene.setX(-5), 0);            
             }
             else if (key.equals("RIGHT"))
             {
                //scene.moveRectangleBy(scene.getX(), 2);
                scene.moveRectangleBy(5, 0);            
             }
            /* else if (key.equals("RIGHT")&& key.equals("UP"))
             { 
                scene.moveRectangleBy(1,-1);
             }*/
          }
          public void keyTyped(KeyEvent event) {}
          public void keyReleased(KeyEvent event) {}
     
     
       }
     
       class TimerListener implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
            scene.moveRectangleBy(scene.getX(), 4);
     
     
          }
     
       }
     
       public RectangleFrame3()
       {
          scene = new RectangleComponent3();
          add(scene);
     
          MouseListener listener = new MousePressListener();
          scene.addMouseListener(listener);
     
          scene.addKeyListener(new KeyStrokeListener());
          scene.setFocusable(true);
     
          ActionListener listener2 = new TimerListener();
     
          final int DELAY = 100; // Milliseconds between timer ticks
          Timer t = new Timer(DELAY, listener2);
          t.start(); 
     
     
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
       }
     
       public int getX(){
          return this.xLocation;
       }
       public void setX(int xLocation){
          this.xLocation = xLocation;
       }
    }

    It seems i need to add the keys pressed into the timerlistener or vice versa but I'm unsure how to start this or where to even begin on how to make the rectangle move automatically with a key press in that direction. Thanks in advance.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Keep track of 4 booleans: one for each arrow key.

    When the user presses one of the arrow keys, set the corresponding boolean to true.

    When the user releases an arrow key, set the corresponding boolean to false.

    In your game loop or Timer event, check those booleans to determine which keys are currently pressed.

    More info here: http://staticvoidgames.com/tutorials...boardInput.jsp
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Edmacelroy (December 4th, 2013)

  4. #3
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Ok here is what I did so far. I guess now that I've created the boolean values, I'm confused now how to determine the keys pressed in the timer event.

    With this code my rectangle moves the direction by holding down a key but I want it to keep moving when the key is released. How would I do this in my code without trying to figure it out from someone else example. I want to know does my code have to be redone using these keyCode variables. It sounds like I'm asking you too solve my issue but what I really want is someone to explain this to me using my code that I developed to better understand how this would work.

    Here are all three part to my code.

    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.Timer;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import javax.swing.KeyStroke;
     
    /** 	 	 	 	 	 	
       This frame contains a moving rectangle.
    */
    public class RectangleFrame3 extends JFrame
    {
       private static final int FRAME_WIDTH = 300;
       private static final int FRAME_HEIGHT = 400;
       private int xLocation = 0;
     
       private RectangleComponent3 snake;
       private boolean right = false;
       private boolean left = false;
       private boolean up = false;
       private boolean down = false;
     
       class MousePressListener implements MouseListener
       {  
          public void mousePressed(MouseEvent event)
          {  
             int x = event.getX();
             int y = event.getY();
             snake.moveRectangleTo(x, y);
          }
     
          // Do-nothing methods
          public void mouseReleased(MouseEvent event) {}
          public void mouseClicked(MouseEvent event) {}
          public void mouseEntered(MouseEvent event) {}
          public void mouseExited(MouseEvent event) {}
       }
     
       class KeyStrokeListener implements KeyListener
       {
          public void keyPressed(KeyEvent event) 
          {
             String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (down = true && key.equals("DOWN"))
             {
     
                snake.moveRectangleBy(snake.getX(), 5);            
             }
             else if (up = true && key.equals("UP"))
             {
     
                snake.moveRectangleBy(0, -5);            
             }
             else if ( left = true && key.equals("LEFT"))
             {
     
                snake.moveRectangleBy(-5, 0);
                //scene.moveRectangleBy(scene.setX(-5), 0);            
             }
             else if (right = true && key.equals("RIGHT"))
             {
     
                //scene.moveRectangleBy(scene.getX(), 2);
                snake.moveRectangleBy(5, 0);            
             }
            /* else if (key.equals("RIGHT")&& key.equals("UP"))
             { 
                scene.moveRectangleBy(1,-1);
             }*/
          }
          public void keyTyped(KeyEvent event) {}
          public void keyReleased(KeyEvent event) {
           String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (down=false && key.equals("DOWN"))
             {
     
                snake.moveRectangleBy(snake.getX(), 4);            
             }
             else if (up = false && key.equals("UP"))
             {
     
                snake.moveRectangleBy(0, 0);            
             }
             else if (left = false && key.equals("LEFT"))
             {
     
                snake.moveRectangleBy(0, 0);
                //snake.moveRectangleBy(snake.setX(-5), 0);            
             }
             else if (right = false && key.equals("RIGHT"))
             {
     
                //snake.moveRectangleBy(scene.getX(), 2);
                snake.moveRectangleBy(0, 0);            
             }
    }
     
     
       }
     
       class TimerListener implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
     
            //scene.moveRectangleBy(scene.getX(), 4);
     
     
          }
     
       }
     
     
       public RectangleFrame3()
       {
          snake = new RectangleComponent3();
          add(snake);
     
          MouseListener listener = new MousePressListener();
          snake.addMouseListener(listener);
     
          snake.addKeyListener(new KeyStrokeListener());
          snake.setFocusable(true);
     
          ActionListener listener2 = new TimerListener();
     
          final int DELAY = 100; // Milliseconds between timer ticks
          Timer t = new Timer(DELAY, listener2);
          t.start(); 
     
     
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
       }
     
       public int getX(){
          return this.xLocation;
       }
       public void setX(int xLocation){
          this.xLocation = xLocation;
       }
    }

    Component

    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import java.awt.Color;
    import java.awt.geom.Ellipse2D;
     
    /**
       This component displays a rectangle that can be moved. 
    */
    public class RectangleComponent3 extends JComponent
    {
       private static final int BOX_X = 100;
       private static final int BOX_Y = 100;
       private static final int BOX_WIDTH = 20;
       private static final int BOX_HEIGHT = 30;
     
       private Rectangle box;
     
       public RectangleComponent3()
       {  
          // The rectangle that the paintComponent method draws 
          box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
       }
     
       public void paintComponent(Graphics g)
       {  
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(box);
          g2.setColor(Color.GREEN);
          g2.fill(box);
     
          Ellipse2D.Double blueRing = new Ellipse2D.Double(10,10, 25, 25);
          g2.setColor(Color.BLUE);
          g2.draw(blueRing);
          g2.fill(blueRing);
       }
     
       /**
          Moves the rectangle to the given location.
          @param x the x-position of the new location
          @param y the y-position of the new location
       */
       public void moveRectangleTo(int x, int y)
       {
          box.setLocation(x, y);
          repaint();      
       }
     
       /**
          Moves the rectangle by a given amount. 
          @param dx the amount to move in the x-direction 
          @param dy the amount to move in the y-direction 
       */
       public void moveRectangleBy(int dx, int dy)
       {
          box.translate(dx, dy);
          repaint();      
       }
    }

    Viewer
    import javax.swing.JFrame;
     
    /**
       This program displays a rectangle that can be moved with the mouse or keyboard.
    */
    public class RectangleViewer3
    {  
       public static void main(String[] args)
       {        
          JFrame frame = new RectangleFrame3();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       }
    }

    I just want to really know am I close?? Do i just have to do something with the timerListener now?? Or do I need to do my code over for the keypressed and timer listeners?? and of course any help anyone is willing to give or suggestions.

  5. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Wait, you want the rectangle to continue moving even after the user lets go of an arrow key?

    If that's the case, then you just need to set the variable once, when the user first presses the key.

    In your Timer listener, you just check the value of those variables, not which keys are down.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Edmacelroy (December 4th, 2013)

  7. #5
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Yes exactly, I want the user to press down the key and when release the rectangle should automatically keep moving in the direction of the arrow key the user pressed and released.

    In your Timer listener, you just check the value of those variables, not which keys are down. - This is where I'm confused, How do I get the TimerListener to check my boolean variables that are in the keyListener

  8. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    The boolean values need to be in a place that both the KeyListener and the Timer's ActionListener can access. They could share a model or refer to an outer class as described here: Action Listeners - Tutorials - Static Void Games
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Edmacelroy (December 4th, 2013)

  10. #7
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    I'm still not getting it.. Do i just have to declare the boolean variables in both the key listener and timer listener classes. I guess the examples I'm just not following because I'm working with keylisteners and timerlisteners and this is working with buttons and I'm having trouble putting the concepts together even though there similar being a beginner I'm just confusing myself more. The examples are helpful I'm just not understanding how to do it. I don't know going into ask the SI tonight but they will probably just say go read and then I just get more lost. Coding is not for everyone I guess.

  11. #8
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Ok so I declared the boolean variables in the RectangleFrame3 class so they can be accessed through that entire class. I tested it and they seem to work somewhat. So I can now get it to automatically move with the arrow keys. Here is the issue I'm having now when I press the left key it takes over, I can't press another key to get it to go in that automatic direction this seems to be because it's the first if statement in my timerlistener is what I think, so how do I get this to work where it will switch direction every time a key is pushed. It will switch directions going down up right left the rectangle automatically goes every direction.

    Code for Frame now

     
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.Timer;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import javax.swing.KeyStroke;
     
    /** 	 	 	 	 	 	
       This frame contains a moving rectangle.
    */
    public class RectangleFrame3 extends JFrame
    {
       private static final int FRAME_WIDTH = 300;
       private static final int FRAME_HEIGHT = 400;
       private int xLocation = 0;
       private boolean right = false;
       private boolean left = false;
       private boolean up = false;
       private boolean down = false;
       private RectangleComponent3 snake;
       private Timer t; 
     
     
      /* class MousePressListener implements MouseListener
       {  
          public void mousePressed(MouseEvent event)
          {  
             int x = event.getX();
             int y = event.getY();
             snake.moveRectangleTo(x, y);
          }
     
          // Do-nothing methods
          public void mouseReleased(MouseEvent event) {}
          public void mouseClicked(MouseEvent event) {}
          public void mouseEntered(MouseEvent event) {}
          public void mouseExited(MouseEvent event) {}
       }*/
     //  public class MyListener implements ActionListener
       class KeyStrokeListener implements KeyListener
       {
     
          public void keyPressed(KeyEvent event) 
          {
             String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (key.equals("DOWN"))
             {
                down = true;
                snake.moveRectangleBy(snake.getX(), 5);            
             }
             else if ( key.equals("UP"))
             {
                up = true;
                snake.moveRectangleBy(0, -5);            
             }
             else if ( key.equals("LEFT"))
             {
                left = true;
                snake.moveRectangleBy(-5, 0);
                //scene.moveRectangleBy(scene.setX(-5), 0);            
             }
             else if (key.equals("RIGHT"))
             {
     
                right = true;
                //scene.moveRectangleBy(scene.getX(), 2);
                snake.moveRectangleBy(5, 0);            
             }
     
          }
          public void keyTyped(KeyEvent event) {}
          public void keyReleased(KeyEvent event) {
     
          }
     
       }
     
       public RectangleFrame3()
       {
          snake = new RectangleComponent3();
          add(snake);
     
         // MouseListener listener = new MousePressListener();
          //snake.addMouseListener(listener);
     
          snake.addKeyListener(new KeyStrokeListener());
          snake.setFocusable(true);
        class TimerListener implements ActionListener
        {
     
          public void actionPerformed(ActionEvent event)
          {
            if (left == true)
            {
            snake.moveRectangleBy(-5, snake.getY());
            right = false;
            down = false;
            up = false;
            }
          else if (left == false)
            {
            snake.moveRectangleBy(0, snake.getY());
            left = false;
            }
     
            if (right == true)
            {
            snake.moveRectangleBy(5, snake.getY());
            left = false;
            up = false;
            down = false;
     
            }
            else if (right == false)
            {
            snake.moveRectangleBy(0, snake.getY());
            right = false;
            }
     
     
            if (up == true)
            {
            snake.moveRectangleBy(snake.getX(), -5);
            left = false;
            down = false;
            right = false;
     
            }
            else if (up == false)
            {
            snake.moveRectangleBy(snake.getX(), 0);
             up = false;
            }
           if (down == true)
            {
            snake.moveRectangleBy(snake.getX(), 5);
            left = false;
            right = false;
            up = false;
     
            } 
              else if (down == false)
            {
            snake.moveRectangleBy(snake.getX(), 0);
             down = false;
            }
     
     
          }
     
       }
     
          TimerListener listener2 = new TimerListener();
     
          final int DELAY = 100; // Milliseconds between timer ticks
          t = new Timer(DELAY, listener2);
          t.start(); 
     
     
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
       }
     
       public int getX(){
          return this.xLocation;
       }
       public void setX(int xLocation){
          this.xLocation = xLocation;
       }
    }


    the part I think needs to be adjusted just unsure how I tried setting all of the boolean values to false for each direction but that didn't seem to work any ideas??

    class TimerListener implements ActionListener
        {
     
          public void actionPerformed(ActionEvent event)
          {
            if (left == true)
            {
            snake.moveRectangleBy(-5, snake.getY());
            right = false;
            down = false;
            up = false;
            }
          else if (left == false)
            {
            snake.moveRectangleBy(0, snake.getY());
            left = false;
            }
     
            if (right == true)
            {
            snake.moveRectangleBy(5, snake.getY());
            left = false;
            up = false;
            down = false;
     
            }
            else if (right == false)
            {
            snake.moveRectangleBy(0, snake.getY());
            right = false;
            }
     
     
            if (up == true)
            {
            snake.moveRectangleBy(snake.getX(), -5);
            left = false;
            down = false;
            right = false;
     
            }
            else if (up == false)
            {
            snake.moveRectangleBy(snake.getX(), 0);
             up = false;
            }
           if (down == true)
            {
            snake.moveRectangleBy(snake.getX(), 5);
            left = false;
            right = false;
            up = false;
     
            } 
              else if (down == false)
            {
            snake.moveRectangleBy(snake.getX(), 0);
             down = false;
            }
     
     
          }
     
       }
     
          TimerListener listener2 = new TimerListener();
     
          final int DELAY = 100; // Milliseconds between timer ticks
          t = new Timer(DELAY, listener2);
          t.start();

  12. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    will switch direction every time a key is pushed
    Turn off all the controlling variables when a key is pressed and turn on the one that should be on for the key that was pressed. This assumes that there are no dependencies between the last key that was pressed and what key was just pressed.
    If you don't understand my answer, don't ignore it, ask a question.

  13. The Following User Says Thank You to Norm For This Useful Post:

    Edmacelroy (December 4th, 2013)

  14. #10
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to get the arrow keys to move rectangle automatically

    Nice, only took me like three days and almost gave up. Finally got it working. Huge Thank you to KevinWorkman for helping me out most of the way and Norm that was it just had to do exactly what you said and awesomeness it's all working.

    This thread is solved just figuring out how to mark it that way.

    Figured it out. Thanks again to both of you

Similar Threads

  1. Please help with Arrow Keys
    By rtucker1023 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2013, 04:58 PM
  2. Code will not work to change speed with the up and down arrow keys
    By rtucker1023 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2013, 04:09 PM
  3. Moving an image around the screen using the arrow keys.
    By nemo in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 19th, 2013, 12:08 AM
  4. [SOLVED] Making an image move with arrow keys
    By Clex19 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 6th, 2012, 09:45 AM
  5. [SOLVED] Arrow keys to navigate a maze in a console program
    By B25Mitch in forum What's Wrong With My Code?
    Replies: 9
    Last Post: January 31st, 2012, 04:58 PM