/*
* Created on 13.12.2004@18:15:50
*
* TODO Explain me ...
*/
package de.tutorials;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
/**
* @author Darimont
*
*/
public class MultiKeyExample extends JFrame {
private final Dimension DIM = new Dimension(320, 240);
private BufferStrategy strategy;
private boolean[] downKeys = new boolean[4];
final static int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;
private int x = 50, y = 50;
private Thread runner = new Thread() {
{
setPriority(MIN_PRIORITY);
}
public void run() {
while (true) {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.clearRect(0, 0, DIM.width, DIM.height);
if (downKeys[UP]) {
y -= 3;
}
if (downKeys[DOWN]) {
y += 3;
}
if (downKeys) {
x -= 3;
}
if (downKeys[RIGHT]) {
x += 3;
}
g.fillOval(x, y, 20, 20);
g.dispose();
strategy.show();
try {
sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public MultiKeyExample() {
super("MultiButtonExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setSize(DIM);
setIgnoreRepaint(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
delegateKeyCommand(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
delegateKeyCommand(e.getKeyCode(), false);
}
private void delegateKeyCommand(int code, boolean isDown) {
switch (code) {
case KeyEvent.VK_UP:
downKeys[UP] = isDown;
break;
case KeyEvent.VK_DOWN:
downKeys[DOWN] = isDown;
break;
case KeyEvent.VK_LEFT:
downKeys = isDown;
break;
case KeyEvent.VK_RIGHT:
downKeys[RIGHT] = isDown;
break;
default:
;
}
}
});
setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
}
public static void main(String[] args) {
new MultiKeyExample().start();
}
/**
*
*/
private void start() {
runner.start();
}
}