I've been trying to work on a Gridworld game for my APCS class, and I've finished everything but key recognition for the Player class.
I've spent hours trying to understand the KeyListener, but I can't.
As you can see in the code below, I've made futile attempts to get it working
Using specific steps, how do I fix my KeyListener problem?
It would be great if you answered my problem in simple words, and in specific steps.
(oh yeah, docs.oracle isn't helping me)
import info.gridworld.actor.Actor; import info.gridworld.grid.Grid; import info.gridworld.grid.Location; import java.util.ArrayList; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import javax.swing.*; public class Player extends Actor { public void act() { } public void move() { Grid<Actor> gr = getGrid(); if (gr == null) return; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (gr.isValid(next)) moveTo(next); else removeSelfFromGrid(); } public Player () { super(); this.addKeyListener(this); } public void moveLeft() { setDirection(270); move(); } public void moveRight() { setDirection(90); move(); } public void moveUp() { setDirection(0); move(); } public void moveDown() { setDirection(180); move(); } public void keyPressed(KeyEvent e) { int keys = e.getKeyCode(); if (keys == KeyEvent.VK_A) { moveLeft(); } else if (keys == KeyEvent.VK_D) { moveRight(); } else if (keys == KeyEvent.VK_W) { moveUp(); } else if (keys == KeyEvent.VK_S) { moveDown(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }