Topic 1 - Variables and Data Types
Topic 2 - Conditionals and Strings
Topic 3 - Loops
Topic 4 - Arrays
Topic 5 - File Handling
Semester 1 Projects
Topic 6 - Classes/Objects and Methods
Topic 7 - ArrayLists
Semester Projects

Part 2a: Adding KeyListeners

In MainClass.java:

keyPressed(KeyEvent e) is a method that comes from the ACM graphics library. It helps us receive a KeyEvent object, which we will be called keyPressed. This KeyEvent Object has lots of information, but what we will need is whether certain keys were pressed.

  • .VK_UP
  • .VK_DOWN
  • .VK_LEFT
  • .VK_RIGHT

Each one of the above is an instance variable of KeyEvent that we can access directly. .getKeyCode() returns which of the above was clicked by the user. The switch statement is another kind of if statement that lets us have different logic for different possibilities. This of each case as an else if statement. For each of the cases, you’ll want to choose what will happen to the SnakeParts. In the following section you will complete the specific methods, but before you move on, try to choose think about what each case will do.

Example:

case KeyEvent.VK_UP:
//should redrawSnake() be called here?
//should moveUp() or moveDown() or moveLeft() or moveRight() be called here?
//should growSnake() be called here?

You will want to either write the pseudocode or call the methods within each case, even though those methods currently don’t do anything.