Tøffelen Tøffelen - 3 months ago 73
Java Question

JavaFX, moving nodes in a GridPane with arrow keys

I am struggling with a maze-like game. I am trying to move a "player"-node around in a GridPane using the arrow keys.

This is my event handler:
public class KeyListener implements EventHandler {

public KeyListener(Player player, int prevX, int prevY, GridPane mapGrid) {
this.player = player;
this.prevX = prevX;
this.prevY = prevY;
this.mapGrid = mapGrid;

// Method for finding rectangle in gridpane:
private Node getNode(GridPane gridPane, int col, int row) {
for (Node node : gridPane.getChildren()) {
if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
return node;
return null;

public void handle(KeyEvent event) {
try {
System.out.println("Player goes " + event.getCode());
if (event.getCode() == KeyCode.DOWN) {
this.player.setPosY(prevY + 1);
Node targetNode = getNode(mapGrid, prevX, prevY+1);
System.out.println(this.player.getPosX() + " " + this.player.getPosY());
mapGrid.add(this.player.playerLook(), player.getPosX(), player.getPosY()); }

Covering only what happens if the arrowdown-key is pressed.
My problem is that the node moves down one row after the first keypress, but after that it does not work any more, but the System.out.println("Player goes " + event.getCode()) sentence is printed.

Any suggestions?


Although I'm not provided enough information, I will make some assumptions.

You should mutate prevX and prevY. If you have a setter method for prevY,

this.player.setPrevY(this.player.getPrevY() + 1);

As explained in the comment, at first iteration, prevY == posY.

Then, it mutates posY into prevY + 1. Therefore posY = prevY + 1. The character moves.

In the second iteration, posY = prevY + 1. Therefore, even when you set this.player.setPosY(prevY + 1), it remains at the same location.