Search code examples
event-handlingimageviewjavafx-8keyevent2d-games

Javafx 8 using KeyEvents with ImageView


I am trying to make a game on Javafx 8 using NetBeans 8.1. The super class of all my game objects is ImageView and I would like to handle key events within a game object instead of in my Scene. The problem is that KeyEvents seem to only work on the Scene and when I add a KeyEvent Handler to my game object nothing happens when I press the keys. Is there anyway to add KeyEvents to any Node, such as an ImageView, and have it work? Below is an example of what I am aiming for (VisibleGameObject extends ImageView):

package hangmanElements;

import javafx.event.EventHandler;
import javafxgame2D.gameObjects.VisibleGameObject;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;


public class HangmanPost extends VisibleGameObject
{
    public HangmanPost()
    {
        super(new Image("/resources/hangmanPost.png"));
        setOriginAtCenter();
        setPosition(100, 250);
        setOnKeyPressed(new EventHandler<KeyEvent>(){

        @Override
        public void handle(KeyEvent event) 
        {
            if(event.getCode() == KeyCode.UP)
            {
                System.out.println("Up pressed MAN!");
            }
        }
    });
}

@Override
public void update() 
{

}
}

Solution

  • Key events are only generated by scene graph nodes when they have keyboard focus. By default, an ImageView does not gain keyboard focus. You need to call

    setFocusTraversable(true);
    

    on the ImageView.