简体   繁体   English

关键侦听器在JApplet中不起作用

[英]Key Listener not working in JApplet

This is a break the brick type of game where the user cannot let the ball fall below the paddle. 这是一种突破性的游戏,用户无法让球掉到桨下。 By the way paddle_x is sets the x coordinate of the paddle. 顺便说一句,paddle_x设置了桨的x坐标。 I have a MouseListener that works very well however, the KeyListener does not. 我有一个效果很好的MouseListener,但是KeyListener却不能。 I am wondering what I am doing wrong and if anyone has any suggestions. 我想知道我做错了什么,是否有人提出建议。

public PaintSurface() {
    addMouseMotionListener(new MouseMotionAdapter() 
    {
        public void mouseMoved(MouseEvent e)
        {
            if (e.getX() - 30 - paddle_x > 5)
                english  = 1.5f;
            else if(e.getX() - 30 - paddle_x < -5)
                english = - 1.5f;
            else
                english = 1.0f;
            paddle_x = e.getX() - 30;
        }
    });
    addKeyListener(new KeyListener() {

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

        }

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

        }

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            if(e.getID() == KeyEvent.KEY_TYPED){
                if(e.getKeyChar() == KeyEvent.VK_RIGHT){
                    paddle_x += 30;
                }
                else if (e.getKeyChar() == KeyEvent.VK_LEFT){
                    paddle_x -= 30;
                }
            }
        }
    });


    ball = new Ball(20);

}

The Component which has a registered KeyListener must have focus for the KeyListener to fire. 具有注册的KeyListener的Component必须具有focusKeyListener才能启动。 Call requestFocus on the Component to request that the component has focus, or use KeyBindings (recommended) 在Component上调用requestFocus以请求该组件具有焦点,或使用KeyBindings (推荐)

In addition, the keyPressed method has a conditional that checks the ID against KeyEvent.KEY_TYPED events (which will never happen). 另外, keyPressed方法具有一个条件,用于根据KeyEvent.KEY_TYPED事件(永远不会发生)检查ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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