Hallo alle zusammen,
ich habe einen Key Listener für ein Spielprojekt geschrieben und ihm meinem GamePanel hinzugefügt.
Leider reagiert der Listener irgendwie nicht und es tut sich nicht.
Ich habe in den KeyPressed und KeyReleased Methoden schon ein paar System.out.println() eingefügt und nichts wird ausgegeben.
Ich weiß nun nicht mehr weiter.
Vielen Dank schonmal für jede Hilfe.
ich habe einen Key Listener für ein Spielprojekt geschrieben und ihm meinem GamePanel hinzugefügt.
Leider reagiert der Listener irgendwie nicht und es tut sich nicht.
Ich habe in den KeyPressed und KeyReleased Methoden schon ein paar System.out.println() eingefügt und nichts wird ausgegeben.
Ich weiß nun nicht mehr weiter.
Vielen Dank schonmal für jede Hilfe.
Java:
public class Controls implements KeyListener {
private Hero hero;
public Controls(Hero hero) {
this.hero = hero;
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_UP) {
hero.setUp(true);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
hero.setDown(true);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
hero.setLeft(true);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
hero.setRight(true);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_UP) {
hero.setUp(false);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
hero.setDown(false);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
hero.setLeft(false);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
hero.setRight(false);
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Java:
public class GamePanel extends JPanel implements Runnable {
private int pWidth;
// size of panel
private int pHeight;
private Image dbImage;
private Graphics dbg;
private Thread animator;
// for the animation
private volatile boolean running = false;
// stops the animation
private volatile boolean gameOver = false;
// for game termination
private Controls controls;
private GameField gameField;
private int[][] map;
public GamePanel(int w, int h ) {
pWidth = w;
pHeight = h;
setBackground(Color.white);
// white background
setPreferredSize( new Dimension(pWidth, pHeight));
// create game components
dbImage = null;
} // end of GamePanel( )
.............
public void doInitializations() {
gameField = new GameField(this, pWidth, pHeight);
controls = new Controls(gameField.getHero());
this.addKeyListener(controls);
}
public void run( ) {
long period;
long beforeTime;
long timeDiff;
long sleepTime;
timeDiff = 0;
period = 10;
beforeTime = System.currentTimeMillis( );
running = true;
doInitializations();
....................