简体   繁体   中英

Java KeyListener is not working in applet

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

    }

}

You need to call update method when keyPressed

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM