Lesson #2-6: Implementing KeyListener
Welcome to Day 3. Today we will be adding code that will allow our game to respond to the user's actions on the keyboard.
Here's how we will approach it:
1. In order for our game to "listen" for key presses and releases, we have to give it a listener.
2. To accomplish #1, we simply need to implement the "KeyListener" interface, and then add the KeyListener in our init() method.
3. Implementing an interface requires that you take every method defined in the KeyListener superclass and add it to your code. These three methods are: keyPressed(), keyReleased(), and keyTyped().
So let's get started by implementing the KeyListener.
1. Go to your StartingClass.java and examine your class declaration:
public class StartingClass extends Applet implements Runnable{
You will notice that you are already implementing the Runnable interface, so you simply add:
", KeyListener" to the end like so:
public class StartingClass extends Applet implements Runnable, KeyListener{
2. When you add this, Java will give you an error saying "KeyListener cannot be resolved to a type". To resolve this error, just import KeyListener.
Welcome to Day 3. Today we will be adding code that will allow our game to respond to the user's actions on the keyboard.
Here's how we will approach it:
1. In order for our game to "listen" for key presses and releases, we have to give it a listener.
2. To accomplish #1, we simply need to implement the "KeyListener" interface, and then add the KeyListener in our init() method.
3. Implementing an interface requires that you take every method defined in the KeyListener superclass and add it to your code. These three methods are: keyPressed(), keyReleased(), and keyTyped().
So let's get started by implementing the KeyListener.
1. Go to your StartingClass.java and examine your class declaration:
public class StartingClass extends Applet implements Runnable{
You will notice that you are already implementing the Runnable interface, so you simply add:
", KeyListener" to the end like so:
public class StartingClass extends Applet implements Runnable, KeyListener{
2. When you add this, Java will give you an error saying "KeyListener cannot be resolved to a type". To resolve this error, just import KeyListener.
3. You will now see an error: "The type StartingClass must implement the inherited abstract method KeyListener.keyReleased(KeyEvent)."
Recall that when you implement an interface, you must take all of its methods and declare them in your class. So you can easily resolve this by choosing: Add unimplemented methods.
Recall that when you implement an interface, you must take all of its methods and declare them in your class. So you can easily resolve this by choosing: Add unimplemented methods.
4. Adding unimplemented methods will do two things: First, it will add the three methods: keyPressed(), keyReleased(), and keyTyped() to your code. These three methods require a KeyEvent object as a parameter. Java is smart enough to import KeyEvent for you.
5. Finally, add this implemented KeyListener to the current Applet by adding to the init() method:
addKeyListener(this);
The resulting code is as follows:
5. Finally, add this implemented KeyListener to the current Applet by adding to the init() method:
addKeyListener(this);
The resulting code is as follows:
Figure 2-10: StartingClass.java
package kiloboltgame;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class StartingClass extends Applet implements Runnable, KeyListener{
@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
}
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class StartingClass extends Applet implements Runnable, KeyListener{
@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
}
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
The first two methods are self-explanatory. keyTyped is slightly more complicated, but you can learn more about it here: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html
Lesson #2-7: Listening for Key Presses
In our 2D-platformer, we will need at least five buttons to start. The four directional arrows will each be a button, and for now we will use the Space Bar for jump.
We are now working in the keyPressed() method. Inside, we will create a switch that will carry out the appropriate action depending on which button is pressed:
We are now working in the keyPressed() method. Inside, we will create a switch that will carry out the appropriate action depending on which button is pressed:
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
Let's examine this in detail. We learned about switches in Unit 1. It is an alternative to a long list of if statements. A switch will compare the key, which is the variable we are checking for, with values, and then carry out the appropriate response.
In this case, the key is e.getKeyCode(). e.getKeyCode() will return the code of the button that you press on the keyboard. (If you were to type System.out.println(e.getKeyCode()); , each time that you press a button, it will display the key code on the console).
What the switch is doing here, then, is comparing the e.getKeyCode() returned from your button presses, and comparing it to multiple cases of values.
In this case, the key is e.getKeyCode(). e.getKeyCode() will return the code of the button that you press on the keyboard. (If you were to type System.out.println(e.getKeyCode()); , each time that you press a button, it will display the key code on the console).
What the switch is doing here, then, is comparing the e.getKeyCode() returned from your button presses, and comparing it to multiple cases of values.
Lesson #2-8: Listening for Key Releases
We will apply the exact same concept to Key Releases.
In this situation, e.getKeyCode() will return the key code upon release of a button (since it is in the keyReleased() method). Then it will carry out an appropriate response depending on which button is released.
In this situation, e.getKeyCode() will return the key code upon release of a button (since it is in the keyReleased() method). Then it will carry out an appropriate response depending on which button is released.
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
At the present, we have no character to actually move or stop. Therefore, we will just output some text to the console like so:
Figure 2-12: StartingClass.java, End of Day 3
package kiloboltgame;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class StartingClass extends Applet implements Runnable, KeyListener {
@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
}
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;
case KeyEvent.VK_LEFT:
System.out.println("Move left");
break;
case KeyEvent.VK_RIGHT:
System.out.println("Move right");
break;
case KeyEvent.VK_SPACE:
System.out.println("Jump");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;
case KeyEvent.VK_LEFT:
System.out.println("Stop moving left");
break;
case KeyEvent.VK_RIGHT:
System.out.println("Stop moving right");
break;
case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class StartingClass extends Applet implements Runnable, KeyListener {
@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
}
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;
case KeyEvent.VK_LEFT:
System.out.println("Move left");
break;
case KeyEvent.VK_RIGHT:
System.out.println("Move right");
break;
case KeyEvent.VK_SPACE:
System.out.println("Jump");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;
case KeyEvent.VK_LEFT:
System.out.println("Stop moving left");
break;
case KeyEvent.VK_RIGHT:
System.out.println("Stop moving right");
break;
case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
That's today's lesson! On Friday, we will be adding the background, our main character, and then add some movement!
Thanks for following my tutorials, and let me know if I can help you in any way!

KiloboltGame - Day 3 |
Instructions on importing projects can be found here.
