在Java中使用setFocusable [英] The use of setFocusable in java

查看:83
本文介绍了在Java中使用setFocusable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了班级开始,在这里按向右箭头键,将移动一个矩形块.但是,此代码仅在添加 setFocusable(true)时有效.我阅读了Java Doc,以及许多以前的Stack Overflow问题,但是我仍然不知道为什么 setFocusable 如此重要.请回答我,仅解释此代码.

I have created class start, where on pressing the Right Arrow key, a rectangle block will move. But this code only works when adding setFocusable(true). I read the Java Doc,and many previous Stack Overflow questions, but I still have no idea why setFocusable is so important. Please answer me explaining this code only.

public class start extends JPanel{

    int x=0, xa=1;

    public start() {

        addKeyListener(new KeyListener(){

            public void keyPressed(KeyEvent ke){

                if(ke.getKeyCode()==KeyEvent.VK_RIGHT){

                    xa=xa+1;

                    repaint();

                }
            }

            public void keyTyped(KeyEvent ke){}

            public void keyReleased(KeyEvent ke){}

        });

        setFocusable(true);

    }

    public void paint(Graphics g){

        super.paint(g);

        g.fillRect(x+xa,100,40,50);

    }

}

推荐答案

但是我仍然不知道为什么setFocusable如此重要.

but I still have no idea why setFocusable is so important.

事件仅分派给具有焦点的组件.因此,只有KeyEvent可以聚焦"并且具有焦点时,才会将其调度到面板.

Events are only dispatched to the component that has focus. So your KeyEvent will only be dispatched to the panel if it is "focusable" and it has focus.

有关更多信息,请参见使用键盘运动有关此主题的信息,包括两种不同的解决方案.

See Motion Using the Keyboard for more information about this topic including two different solutions.

这篇关于在Java中使用setFocusable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆