I have this key listener in my application, and it wont work. This is my first key listener in an application, however I have done a mouse listener in one before. Anyway here is my code:
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class DropGame extends JPanel implements KeyListener {
int x = 50, y = 50;
int velocity = 1;
int accel = 2;
int friction = 1;
public void game() {
// TODO Auto-generated method stub
addKeyListener(this);
repaint ();
}
public void paintComponent (Graphics g){
super.paintComponent(g);
//g.drawString("In Game", 250, 150);
g.fillRect (x,y,20,20);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
System.out.print("Move");
if (key == KeyEvent.VK_D){
int move;
velocity += accel;
move = velocity - friction;
x += move;
}
if (key == KeyEvent.VK_LEFT){
int move;
velocity += accel;
move = velocity - friction;
x -= move;
}
repaint();
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
for some reason the key pressed method will not activate. I have added the listener and everything.
Thanks for the help.