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.