本帖最后由 yaojianquansb 于 2010-08-16 11:23:06 编辑

解决方案 »

  1.   

    焦点肯定在窗体可用控件的第一个上面,根据你上面的代码,焦点应该在button1上,当你打开窗体,你可以通过tab键进行焦点迁移。
      

  2.   

    是的, public ActionPanel(){
    JButton b1 = new JButton("button1");
    JButton b2 = new JButton("button2");
         add(b1);
         add(b2);
         System.out.println(b1.isFocusOwner()); 
                //在构造方法里检测一下b1按钮,就是第一个按钮是否有焦点,为啥输出false?
    }
      

  3.   

    你这样frame还没有渲染完,frame不确定将焦点定义在哪个组件上,所以你直接在添加过程中获取是不行的。
    其次isFocusOwner()这个方法的源码是调用返回的是hasFocus,是返回的是键盘事件的焦点。
    所以我们需要有个键盘或者鼠标的触发事件,才能得到这个值。import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Test{
     static JButton b1 = new JButton("button1");
     static  JButton b2 = new JButton("button2");
        public static void main(String args[]){
         Test test=new  Test();
            ActionFrame frame = test.new ActionFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            System.out.println(frame.isFocusOwner());
            System.out.println(b1.isFocusOwner());
            System.out.println(b2.isFocusOwner());
        }
        class ActionPanel extends JPanel{
            public ActionPanel(){
                add(b1);
                add(b2);
            }
        }
        class ActionFrame extends JFrame{
            public ActionFrame(){
                setTitle("ActionTest");
                setSize(450,300);setLocation(550,350);
                ActionPanel panel = new ActionPanel();
                getContentPane().add(panel);
            }
        }
    }我给你稍微改了下,试试看!
      

  4.   

    上面的代码应该也是输出false。
    是因为没有触发键盘或者鼠标事件。
    在System.out.println(frame.isFocusOwner());
            System.out.println(b1.isFocusOwner());
            System.out.println(b2.isFocusOwner());
    代码前加入b1.doClick();