So I got 2 classes called Viewer and PaintWindow. In my case, the Viewer class acts as an controller while I use my PaintWindow class to paint things on a JPanel.
Now I'm trying to put together a little game but I don't understand how to implement the KeyListener to be able to control the game. What I want is a listener listeing for a keyEvent to happen so I can decide what will happen. This is how my code looks like:
Viewer:
public void run() {
System.out.println("Viewer Run");
cloud1 = new ImageIcon("src/images/cloud.png");
cloud2 = new ImageIcon("src/images/cloud.png");
background1 = new ImageIcon("src/images/background.png");
playerStill = new ImageIcon("src/images/still.png");
playerRight = new ImageIcon("src/images/right.png");
playerLeft = new ImageIcon("src/images/left.png");
paintWindow = new PaintWindow(background1);
paintWindow.showImage(playerStill, 30, 370);
paintWindow.addKeyListener(new KeyTimerListener());
paintWindow.startAlarm();
}
/*
* Lyssnar på vad som händer när man trycker en viss knapp
*/
private class KeyTimerListener implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == 37){
System.out.print("Left");
}
else if (keyCode == 39){
System.out.print("Right");
}
else if (keyCode == 32 ){
System.out.print("JUMP");
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
}
This is a part from my PaintWindow class:
public void addKeyListener(KeyListener listener){
this.listener.add(listener);
}
private class AT extends Thread {
KeyEvent keyevent;
public void run() {
try {
Thread.sleep(1);
}catch(InterruptedException e) {
}
for(KeyListener al : listener) {
al.keyPressed(keyevent);//<-----------------------------
}
thread = null;
}
}
public void startAlarm() {
if(thread==null) {
thread = new AT();
thread.start();
}
}
I get a nullpointer exception as my KeyEvent is null. Sure I could define it as being a specific key, but that doesn't really help me here.
What have I missed?