隐藏的线程实现

来源:互联网 发布:清华大学网络公开课 编辑:程序博客网 时间:2024/05/16 19:02

Java实现QQ那样的自动隐藏其实也不是很难。
主要思想就是检测窗口在屏幕上的位置。当窗口靠边的时候就重新设置窗口的位置。
导包就省略了……
public class AutoHideFrame extends JFrame implements Runnable, MouseListener {
    private Thread thread = null;

    private boolean hide = false;

    private Toolkit tk = getToolkit();

    private final int TOP = 1;

    private final int RIGHT = 2;

    private int direction;

    AutoHideFrame() {
        thread = new Thread(this);
        this.setTitle("Auto Hide");
        this.setResizable(false);
        this.setSize(200, 600);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
        this.addMouseListener(this);
        thread.start();
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new AutoHideFrame();

    }
    

    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            if (Thread.currentThread().equals(thread)) {
                System.out.println("Thread Working...");
                double x = getLocation().getX(); //获取当前窗口在屏幕上的X坐标
                double y = getLocation().getY();//获取当前窗口在屏幕上的Y坐标
                System.out.println("x:=" + x + " y=" + y);
                // 靠顶隐藏
                if (y <= 0) {                               //判断窗口靠顶
                    this.setLocation((int) x,
                            (int) (-getSize().getHeight() + 10)); //重新设置窗口坐标。+ 10是为了露出来一点
                    hide = true;                                             //方便监听鼠标移入事件
                    direction = TOP;
                }
                //靠右边隐藏
                if (x >= tk.getScreenSize().getWidth() - getSize().getWidth()) {
                    this.setLocation((int) (tk.getScreenSize().getWidth() - 5),
                            (int) y);
                    hide = true;
                    direction = RIGHT;
                }
            }

        }
    }

    public void mouseClicked(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub
        if (hide == true) {
            if (direction == TOP) {
                this.setLocation((int) getLocation().getX(), 1);

            }
            if (direction == RIGHT) {
                this.setLocation((int) (tk.getScreenSize().getWidth()
                        - getSize().getWidth()-5), (int)getLocation().getY());
            }
            hide = false;
        }

    }
//不关注的方法被删除了,没有写出来。
    

}