Reputation: 11
I'm new to Java so please forgive me asking for help, but after 4 hours of searching for a solution I'm really getting desperate.
I'm currently setting up a game and want to implement key controls. I tried to do this via KeyListener
and KeyEventDispatcher
but I just can't get it to work.
The KeyListener
just won't react. I think that the method that is supposed to use it has the focus.
Here's the code:
public class Sins extends JFrame implements KeyEventDispatcher {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED ) {
if(KeyEvent.VK_UP == e.getID()){
System.exit(0);
}
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
if(KeyEvent.VK_UP == e.getID()){
System.exit(0);
}
} else if (e.getID() == KeyEvent.KEY_TYPED) {
if(KeyEvent.VK_UP == e.getID()){
System.exit(0);
}
}
return false;
}
and here is the method where it is supposed to be working at:
public void run() {
setFocusable(true);
backgroundGraphics = (Graphics2D) background.getGraphics();
long fpsWait = (long) (1.0 / 30 * 1000);
requestFocusInWindow();
main: while (isRunning==true) {
long renderStart = System.nanoTime();
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(this);
x++;
requestFocusInWindow();
// Update Graphics
do {
Graphics2D bg = getBuffer();
if (isRunning == false) {
break main;
}
renderGame(backgroundGraphics); // this calls your draw method
if (scale != 1) {
bg.drawImage(background, 0, 0, width * scale, height
* scale, 0, 0, width, height, null);
} else {
bg.drawImage(background, 0, 0, null);
}
bg.dispose();
requestFocusInWindow();
this.requestFocus();
if(x ==5000){
isRunning=false;
}
} while (!updateScreen());
// Better do some FPS limiting here
long renderTime = (System.nanoTime() - renderStart) / 10000;
try {
Thread.sleep(Math.max(0, fpsWait - renderTime));
} catch (InterruptedException e) {
Thread.interrupted();
break;
}
renderTime = (System.nanoTime() - renderStart) / 10000;
}
this.dispose();
System.exit(0);
}
The program is currently closing itself after counting up to 5000. For test purposes I'm trying to close it via the up button but it just won't close that way. I would really appreciate some help, as I said I'm new to Java.
Upvotes: 1
Views: 352
Reputation: 347332
The first problem you were facing with KeyListener
is a well know and well documented (here on SO especially). KeyListener
will only on respond if the component they are attached to is focusable and has keyboard focus. Think of a text field, when it doesn't have focus, it won't update.
Your second problem is using the KeyBoardFocusManager
, which is simply overkill for this problem.
Instead, you should make use of the [Key Bindings] API, which is simpler the having to monitor the KeyBoardFocusManager
and more robust then KeyListeners
Upvotes: 1