I have to code a simple game for my class, but I have a problem with moving my 'character'. It works perfectly fine, but only for the first time I press one of the arrow keys. After that it doesn't respond anymore. Please tell me how to make it work every time I press the key. Thanks!
public void startGame()
{
gRow = 1;
gCol = 1;
setUpLabels();
gp.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent keyEvent) {
switch(keyEvent.getCode()){
case DOWN:
{
labels[gRow + 1][gCol].getStyleClass().add("guard");
labels[gRow + 1][gCol].setText("G");
gRow++;
}
break;
case UP:
{
labels[gRow - 1][gCol].getStyleClass().add("guard");
labels[gRow - 1][gCol].setText("G");
gRow--;
}
break;
case RIGHT:
{
labels[gRow][gCol+1].getStyleClass().add("guard");
labels[gRow][gCol+1].setText("G");
gCol++;
}
break;
case LEFT:
{
labels[gRow][gCol-1].getStyleClass().add("guard");
labels[gRow][gCol-1].setText("G");
gCol--;
}
break;
}
}
});
gp.requestFocus();
This is my startGame() method in GUI class, where my setOnKeyPressed() method is placed.