public class Keylistener extends JPanel implements ActionListener, KeyListener {
/**
* SerialUID.
*/
private static final long serialVersionUID = 1L;
private final int timer = 5;
private final int m = -1;
private final int n = 1;
private int x = 0, y = 0, velx = 0, vely = 0;
private final int Startposition1 = 100;
private final int Startposition2 = 100;
private int z = Startposition1, q = Startposition2, velz = 0, velq = 0;
final int l = 10;
private Timer t = new Timer(timer, (ActionListener) this);
public Keylistener() {
t.start();
addKeyListener((KeyListener) this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint(final Graphics g) {
super.paint(g);
int h = getWidth();
int ö = getHeight();
for (int x = 0; x < h; ++x) {
for (int y = 0; y < ö; ++y) {
g.setColor(Color.black);
Graphics2D g2 = (Graphics2D)g;
g2.fillRect(x * 10 + x,
y * 10 + y, 10,
10);
}}
this.setBackground(Color.green);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.blue);
g2.fillRect(x, y, l, l);
g2.fillRect(z, q, l, l);
}
/**
* @param e
* ActionEvent e
* @Override
*/
public final void actionPerformed(final ActionEvent e) {
repaint();
x += velx;
y += vely;
repaint();
z += velz;
q += velq;
}
public final void up() {
vely = m;
velx = 0;
}
public final void down() {
vely = n;
velx = 0;
}
public final void left() {
velx = m;
vely = 0;
}
public final void right() {
velx = n;
vely = 0;
}
public final void up2() {
velq = m;
velz = 0;
}
public final void down2() {
velq = n;
velz = 0;
}
public final void left2() {
velz = m;
velq = 0;
}
public final void right2() {
velz = n;
velq = 0;
}
/**
* @param e
* KeyEvent e
* @Override
*/
public final void keyPressed(final KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
up2();
}
if (code == KeyEvent.VK_DOWN) {
down2();
}
if (code == KeyEvent.VK_RIGHT) {
right2();
}
if (code == KeyEvent.VK_LEFT) {
left2();
}
if (code == KeyEvent.VK_W) {
up();
}
if (code == KeyEvent.VK_S) {
down();
}
if (code == KeyEvent.VK_D) {
right();
}
if (code == KeyEvent.VK_A) {
left();
}
}
/**
* @param e
* KeyEvent e
* @Override
*/
public final void keyTyped(final KeyEvent e) {
}
/**
* @param e
* KeyEvent e
* @Override
*/
public final void keyReleased(final KeyEvent e) {
}
}