I was thinking more on the lines of:
(functional)
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends Canvas implements KeyListener {
private static final int
FIRE = 1,
FORWARD = 2,
REVERSE = 4,
TURN_LEFT = 8,
TURN_RIGHT = 16;
private int ACTION = 0;
public static void main(String[] args) {
new Test();
}
public Test() {
JFrame w = new JFrame("Test");
JPanel p = (JPanel)w.getContentPane();
p.setSize(640,480);
p.add(this);
w.setBounds(0,0,640,480);
w.setVisible(true);
w.setResizable(false);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
requestFocus();
createBufferStrategy(2);
BufferStrategy strategy = getBufferStrategy();
Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
while(true) {
g.setColor(Color.WHITE);
g.fillRect(0,0,640,480);
g.setColor(Color.BLACK);
if((ACTION&FIRE)==FIRE)
g.drawString("User is firing.",20,20);
if((ACTION&FORWARD)==FORWARD)
g.drawString("User is going forward.",20,40);
if((ACTION&REVERSE)==REVERSE)
g.drawString("User is reversing.",20,60);
if((ACTION&TURN_LEFT)==TURN_LEFT)
g.drawString("User is turning left.",20,80);
if((ACTION&TURN_RIGHT)==TURN_RIGHT)
g.drawString("User is turning right.",20,100);
g.drawString("Action value is :"+ACTION+"\n\n",20,120);
strategy.show();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent arg0) {
}
public void keyPressed(KeyEvent arg0) {
switch(arg0.getKeyCode()) {
case KeyEvent.VK_SPACE: ACTION = ACTION | FIRE; break;
case KeyEvent.VK_W: ACTION = ACTION | FORWARD; break;
case KeyEvent.VK_S: ACTION = ACTION | REVERSE; break;
case KeyEvent.VK_A: ACTION = ACTION | TURN_LEFT; break;
case KeyEvent.VK_D: ACTION = ACTION | TURN_RIGHT; break;
}
}
public void keyReleased(KeyEvent arg0) {
switch(arg0.getKeyCode()) {
case KeyEvent.VK_SPACE: ACTION = ACTION ^ FIRE; break;
case KeyEvent.VK_W: ACTION = ACTION ^ FORWARD; break;
case KeyEvent.VK_S: ACTION = ACTION ^ REVERSE; break;
case KeyEvent.VK_A: ACTION = ACTION ^ TURN_LEFT; break;
case KeyEvent.VK_D: ACTION = ACTION ^ TURN_RIGHT; break;
}
}
}