3

我有这个代码:

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;

    import javax.swing.JApplet;


    public class applet extends JApplet implements KeyListener, MouseListener{
        int a = 0;
        int b = 0;
        public void init(){
            setSize(500,500);
            addKeyListener( this );
             addMouseListener( this );
        }
        public void paint(Graphics g){
            g.setColor(Color.BLUE);
            g.fillRect(a, b, 400, 400);
        }
        @Override
        public void keyPressed(KeyEvent e) {
        System.out.println("Hello!")    
switch(e.getKeyCode()){
                case KeyEvent.VK_DOWN: a -= 5;
                break;
                case KeyEvent.VK_UP: a += 5;
                break;
                case KeyEvent.VK_RIGHT: b += 5;
                break;
                case KeyEvent.VK_LEFT: b -= 5;
                break;
            }
            repaint();
        }
        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

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

        }
        @Override
        public void mouseClicked(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
    }

从我的调试 println 代码可以看出,它甚至没有到达 switch 语句。为什么会发生这种情况,我该怎么做才能解决这个问题?如果这太宽泛,请不要讨厌,因为我是这个话题的完全菜鸟

4

1 回答 1

6

KeyListener只有当它注册的组件是可聚焦的并且有焦点时才会触发事件。

JApplet有一个在小程序顶部JRootPane添加一个JLayeredPane内容窗格(除其他外),这可能意味着关键侦听器可能永远无法开始通知事件(因为其他元素正在阻止它)。

相反,使用键绑定

于 2013-07-16T00:15:14.347 回答