Move the Ball and Trace the Taken Route
Add methods to move the balls on screen with arrow keys and trace the path taken.
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
).
- 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()
- Add code to the
keyReleased()
method of theKeyAdapter
to:
- Create a character called
c
, initialized by getting the character frome
. Use KeyEvent’sgetKeyChar()
method. - Print
c
to the output console usingSystem.out.println()
.
...
private void initGUI() {
...
addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
__________ c = e.____________();
_________________;
}
});
...
Get hands-on with 1200+ tech skills courses.