Move the Ball and Trace the Taken Route

Key listeners

The program will need to respond when a cursor key is pressed - up, down, left, and right - to move the ball through the maze.

Listening for keystrokes

Up until now, there has been a method kept for tracing the path, but the path isn’t visible on the maze yet. Now you will add code to move the green ball through the maze making the chosen path visible.

To make MazeGenerator listen for keystrokes from the keyboard, add a key listener. Adding key listeners is very similar to adding action listeners.

Instead of adding the key listener to a button, you will add the key listener to the window itself (the JFrame).

  1. In the listeners section of initGUI(), add a key listener to the window by inserting code exactly as shown.
    ...
private void initGUI() {
    ...
    // listeners
    addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {

        }
    });
    ...

A KeyEvent holds information about the key that was pressed. For example, to get the character that was typed, from a KeyEvent called e, use:

e.getKeyChar()
  1. Add code to the keyReleased() method of the KeyAdapter to:
  • Create a character called c, initialized by getting the character from e. Use KeyEvent’s getKeyChar() method.
  • Print c to the output console using System.out.println().
    ...
private void initGUI() {
      ...
    addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            __________ c = e.____________();
            _________________;
        }
    });
      ...

Get hands-on with 1200+ tech skills courses.