0

Can anyone tell me what is wrong? I'm trying to make the square move up and down. When i run the applet, the square is created at the right spot but when i press the UP key or DOWN key nothing happens.

    package pong;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class pong extends Applet implements KeyListener
{
    private Rectangle rect = null;
    private int key = 0;

    public void init()
    {
        rect = new Rectangle(0,0,10,10);    
        addKeyListener(this);
    }

    public void paint(Graphics g)
    {
        setSize(200,200);
        Graphics2D g2 = (Graphics2D)g;
        g2.fill(rect);
    }

    @Override
    public void keyPressed(KeyEvent e) 
    {
        key = e.getKeyCode();
    }

    public void update()
    {
        if(key == KeyEvent.VK_UP)
        {
            rect.setLocation(rect.x, rect.y - 2);
        }
        else if(key == KeyEvent.VK_DOWN)
        {
            rect.setLocation(rect.x, rect.y + 2);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    FYI: the applet plugin is no longer supported, effectively making applet deprecated. I'd consider starting with Swing (and use the key bindings API) or JavaFX – MadProgrammer Feb 14 '16 at 01:51
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. 3) For Swing, we typically use [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) rather than the lower level `KeyListener`. – Andrew Thompson Feb 16 '16 at 01:03

1 Answers1

0

You need to call update method when keyPressed

 @Override
    public void keyPressed(KeyEvent e) 
    {
        key = e.getKeyCode();
           update();

    }
Abdelhak
  • 8,299
  • 4
  • 22
  • 36