I'm working on a game in Java. In the game, the player will be able to control a tank that moves on the screen using Key Bindings. Each arrow-button moves the tank in a different direction.
I'd like to know, if the way I used Key Bindings in the program, is correct and isn't supposed to cause problems with the EDT or with anything else later on.
I will explain in short the structure of the program, and how I used Key Bindings.
There's a
Board
class, a class that extendsJPanel
and has most of the game logic. It also displays the graphics.There's a
KeyBindingsRunnabel
class, a class that implementsRunnable
. This class has all the KeyBindings code.Board
contains the game-loop. The game loop happens inside a thread. In the thread, but before the game loop, a new thread is created and started, that thread runsKeyBindingsRunnabel
.
(There's also a Main class that extends JFrame and creates an instance of Board, but that's irrelevant).
I'll demonstrate all of this in short:
Here is the code for the KeyBindingsRunnabel
class:
public class KeyBindingsRunnable implements Runnable {
Board b;
Action upAction,leftAction;
InputMap inputMap;
ActionMap actionMap;
public KeyBindingsRunnable (Board b){
this.b = b;
inputMap = b.getInputMap();
actionMap = b.getActionMap();
public void run() {
leftAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
// Code to move tank left.
}
};
rightAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
// Code to move tank right.
}
};
inputMap.put(KeyStroke.getKeyStroke("LEFT"),"leftAction");
inputMap.put(KeyStroke.getKeyStroke("RIGHT"),"rightAction");
actionMap.put("leftAction",leftAction);
actionMap.put("rightAction",rightAction);
}
}
The way the Board class uses KeyBindingsRunnable
is as follows:
The Board class also implements Runnable
. It contains a thread declaration in it's constructor:
Thread gameloop = new Thread(this);
gameloop.start();
In Board's run() method, there are two thing: a game-loop, and before the loop, the creation of a new thread that runs KeyBindingRunnable.
The run() method of Board
looks like this:
public void run(){
Thread keyBindingsThread = new Thread(new KeyBindingRunnable(this));
keyBindingsThread.start();
while(gameIsRunning){
// The loop.
// .....
}
}
My question is: Is this the correct way to use Key Bindings without interupting with the EDT, and in general the correct way?
Is there a more effecient/safer/shorter way of using Key Bindings in a 2D game?
Thanks a lot :)