再问问public boolean isFocusCycleRoot(Container container)和public void requestFocus()这两个方法,是干什么用的????

解决方案 »

  1.   

    据我理解临时性焦点改变,就是比如一个JButton在目前的窗口中,是有焦点的,这时候你点击了其他的窗口,所以目前窗口失去了焦点,但是如果你从新再点击它的时候,这个窗体的焦点还是在这个JButton上。永久改变就是你按Tab或者这个窗口的其他组建调用了requestFocus()方法,把焦点从JButton上转移走了,这时候JButton就是永久性焦点事件。
    按Tab和requestFocus()方法都是可以改变焦点的,Tab会使焦点自动转向下一个应该遍历到的组件,而这个遍历的顺序是JDK里面给你写好了的,不用你操心,一般都是从左到右,从上到下的原则。而requestFocus()是可以通过组件对象调用的。调用后,这个组件就获得了焦点。
    public boolean isFocusCycleRoot(Container container)可以返回容器(一般是JFrame)里面的组件是否具有目前的焦点,如果是返回true。
    下面这个程序就是用的requestFocus()写的,加上了线程,1秒换一个JButton获得焦点。
    import java.awt.*;
    import javax.swing.*;public class Test6 extends JFrame implements Runnable
    {
    static int count=0;
    Container con;
    JButton jb1,jb2,jb3;
    JPanel jp;
    Thread thread;

    public Test6()
    {
    con = this.getContentPane();
    jp = new JPanel();
    jb1 = new JButton("Button1");
    jb2 = new JButton("Button2");
    jb3 = new JButton("Button3");

    jp.add(jb1);
    jp.add(jb2);
    jp.add(jb3);

    con.add(jp);

    setBounds(300,300,300,300);
    show();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void run()
    {
    while(true)
    {
    if(count%3==0)
    {
    this.jb1.requestFocus();
    }
    else if(count%3==1)
    {
    this.jb2.requestFocus();
    }
    else
    {
    this.jb3.requestFocus();
    }
    count++;
    try{thread.sleep(1000);}catch(Exception e){}
    }
    }

    public static void main(String[] args)
    {
    Thread thread = new Thread(new Test6());
    thread.start();
    }
    }
    有问题,尤其知道方法名的时候多去查API,这样才能提高的快。