Java KeyListener在applet中不起作用

时间:2016-02-13 23:12:55

标签: java applet awt keylistener

谁能告诉我有什么问题?我试图让广场上下移动。 当我运行applet时,正方形会在正确的位置创建,但是当我按下UP键或DOWN键时没有任何反应。

    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

    }

}

1 个答案:

答案 0 :(得分:0)

您需要在keyPressed

时调用update方法
 @Override
    public void keyPressed(KeyEvent e) 
    {
        key = e.getKeyCode();
           update();

    }