Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

KeyListener in game  RSS feed

 
vikas Ranjane
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys
I am trying add an actionlistener like

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpriteTest implements KeyListener {

public static void main(String args[])
{
SpriteTest test = new SpriteTest();
test.run();


}

// var declaration is here

public void run()
{
screen = new SimpleScreenManager();


try{

DisplayMode dm = screen.getFirstCompatibleMode(myModes);
screen.setFullScreen(dm);

Window w = screen.getFullScreenWindow();
// w.setFocusTraversalKeysEnabled(false);
System.out.print(w.isFocusable());
w.addKeyListener(new SpriteTest()); // or this
track = new SoundTrack();
loadImages();
animationLoop();
}finally{screen.restoreScreen();}
}

public void keyTyped(KeyEvent e)
{
int key = e.getKeyCode();
System.out.print("hi"+key+e);
if (key == KeyEvent.VK_SPACE)
{

track.start(1,1);

}else
{
track.stop();
}
}
}


but my keyListener is not working
the keyCode value is always 0
prog generate following
exception in thread awt-eventqueue-0 java.lang.nullpointerexception + 10 to 15 lines of stuff


pz anybody help me
report.jpg
[Thumbnail for report.jpg]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> the keyCode value is always 0

re-read the apidocs for KeyEvent, where it is clearly defined

http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html
 
vikas Ranjane
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Michael

fixed that problem for keyTyped

and inserted that code in keyPressed(Event e)

public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
System.out.print("hi"+key+e);
if (key == KeyEvent.VK_SPACE)
{

track.start(1,1); /// <----error here

}else
{
track.stop();
}

but now though i am getting the correct keyCode value
program is still generating those

exception in thread "awt-eventqueue-0" java.lang.nullpointerexception report at
track.start(1,1);
I have created instance track before registering the keylistener

and the track.start(1,1) works perfectly outside those key listener methods


HELp pz
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags. That makes your code much easier to read.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
w.addKeyListener(new SpriteTest()); // or this

use the 'this' part
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!