0

当我启动我的小程序时,我没有得到关键监听器的响应。我该如何解决?下面是代码。

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;

public class Main extends Applet {
private static final long serialVersionUID = 1L;
public String mode = "";
public Graphic gr;

public void init() {
    this.setSize(400, 400);
    gr = new Graphic();
    this.add(gr);
    gr.addKeyListener(new MyKeyListener());
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
                    gr.requestFocus();
            gr.repaint();
        }

    };
    new Timer().scheduleAtFixedRate(timerTask, 0, 1000 / 5);

}

public void paint(Graphics g) {

}

private class MyKeyListener extends KeyAdapter {
    public MyKeyListener(){
        System.out.println("HELLO");
    }
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            gr.direction = Graphic.Direction.up;
            gr.move();

            break;
        case KeyEvent.VK_DOWN:
            gr.direction = Graphic.Direction.down;
            gr.move();
            break;
        case KeyEvent.VK_LEFT:
            gr.direction = Graphic.Direction.left;
            gr.move();
            break;
        case KeyEvent.VK_RIGHT:
            gr.direction = Graphic.Direction.right;
            gr.move();
            break;
        }
    }

    public void keyReleased(KeyEvent e) {

    }
}
}
4

1 回答 1

2
    import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TTest extends Applet{
    @Override
    public void init() {
        // TODO Auto-generated method stub
        super.init();
        this.setSize(400, 400);
        addKeyListener(new KeyListener());

    }
    class KeyListener extends KeyAdapter{
        public KeyListener(){

        }

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            super.keyPressed(e);
            switch(e.getKeyCode()){
            case KeyEvent.VK_UP:
                System.out.println("Pressed up arrow!");
                break;
            case KeyEvent.VK_DOWN:
                System.out.println("Pressed down arrow!");
                break;
            default:
                System.out.println("You pressed: " + e.getKeyCode());
            }
        }

    }
}

您必须将键事件侦听器添加到小程序本身而不是图形对象。但是,我认为可以将鼠标事件侦听器添加到小程序以外的对象

于 2012-11-27T23:50:39.990 回答