3

I am making a graphics where the circle should move with arrow keys but I checked my code yet can't find the problem. The applet is working and initializing but the circle is not moving when i pressed the arrow keys. Can you help me here?

public class second extends JPanel implements ActionListener, KeyListener{

Timer t = new Timer(5,this);
double x = 0, y = 0, velx = 0, vely = 0;

public second() {
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Ellipse2D.Double(x,y,40, 40));    
}

public void actionPerformed(ActionEvent e){
    repaint();
    x += velx;
    y += vely;
}

public void up(){
    vely = -1.5;
    velx = 0;        
}

public void down(){
    vely = 1.5;
    vely = 0;
}

public void left(){
    velx = -1.5;
    vely = 0;
}

public void right(){
    velx = 1.5;
    vely = 0;
}

public void keyPressed(KeyEvent e){
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP){
        up();
    }
    if (code == KeyEvent.VK_DOWN){
        down();
    }
    if (code == KeyEvent.VK_LEFT){
        left();
    }
    if (code == KeyEvent.VK_RIGHT){
        right();
    }
    repaint();
}

public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) {}

}
TZHX
  • 5,291
  • 15
  • 47
  • 56
anon
  • 31
  • 3
  • 1
    Use key bindings, avoid `KeyListener` pitfalls. [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Apr 16 '15 at 09:30
  • can you provide the complete program? I can't seem to run it correctly. – tim Apr 16 '15 at 09:48
  • 1
    For [example](http://stackoverflow.com/questions/16911722/continuous-movement-with-a-single-key-press/16916810#16916810) and [example](http://stackoverflow.com/questions/28228121/how-to-move-move-a-rectangle-in-jframe-using-keylistener/28228180#28228180) – MadProgrammer Apr 16 '15 at 09:49

0 Answers0