在程序运行的时候焦点总是在窗口上,我想改变它,让焦点移到画布(canva)
我在文档上找到这个函数setFocusable(true),但应用起来不是很使!!!
大家来帮下忙吧。

解决方案 »

  1.   

    还有requestFocusInWindow() 
      

  2.   

    我把代码贴了上来,大家在帮忙看一下吧。
    public class Gamebank extends Canvas implements KeyListener
    {
         Mainshare tu = new shangTu();
    public Gamebank()
    {
    setSize(200,400);
    setVisible(true);
    setBackground(Color.BLACK);
    tu.setPlace();
    addKeyListener(this);
    //requestFocus(true);//设置画布的焦点
        requestFocusInWindow();// 这两个设置都不好使
        
    }
          public static void main(String[] a)
        {
        
               JFrame f = new JFrame(); 
               f.setSize(220,440);
               f.setVisible(true);
               f.setResizable(false);//设置窗口可变
               f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               f.getContentPane().add(game);
            }   
      

  3.   

    public class Gamebank extends Canvas implements KeyListener
    {
         Mainshare tu = new shangTu();
    public Gamebank()
    {
    setSize(200,400);
    setVisible(true);
    setBackground(Color.BLACK);
    tu.setPlace();
    addKeyListener(this);
    //requestFocus(true);//设置画布的焦点
         //requestFocusInWindow();// 这两个设置都不好使
        
    }
          public static void main(String[] a)
        {
        
               JFrame f = new JFrame(); 
               f.setSize(220,440);
               f.setVisible(true);
               f.setResizable(false);//设置窗口可变
               f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               f.getContentPane().add(game);           game.requestFocusInWindow();//         }   

    这样行吗,我最近也在研究此问题,但你没把代码传完整,我们怎么帮你调试。,至少你的代码也要运行通过。
      

  4.   

    好使了,是初始化地问题。可为什么必须得先添加完该画布到窗口上,然后才能设置画布的焦点的呢??
    请看以下的代码
    public static void main(String[] a)
        {
        
               JFrame f = new JFrame();
               Gamebank game = new Gamebank();
               f.setSize(220,440);
               f.setVisible(true);
               f.setResizable(false);//设置窗口可变
               f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /////////////////////////////////////////
                //game.requestFocus(true);    //在没添加之前设置的焦点都不好使。   
               //game.requestFocusInWindow();
    ////////////////////////////////////////
               f.getContentPane().add(game);
           
             game.requestFocus(true);//而这个就好使了
             game.requestFocusInWindow();//这个也好使了,
            }
    不过还是先谢谢你了啊。你能能否给我讲一下这个焦点是什么回事吗??