import java.awt.Point;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JFrame;import javax.swing.Timer;public class MyFrame extends JFrame implements ActionListener { private Rectangle rect; // 表單離螢幕左邊的距離 private int left; // 表單離螢幕頂部的距離 private int top; // 表單的寬 private int width; // 表單的高 private int height; // 滑鼠在表單的位置 private Point point; private Timer timer = new Timer(10, this); public MyFrame() { timer.start(); } public void actionPerformed(ActionEvent e) { left = getLocationOnScreen().x; top = getLocationOnScreen().y; width = getWidth(); height = getHeight(); // 擷取表單的輪廓 rect = new Rectangle(0, 0, width, height); // 擷取滑鼠在表單的位置 point = getMousePosition(); if ((top < 0) && isPtInRect(rect, point)) { // 當滑鼠在當前表單內,並且表單的Top屬性小於0 // 設定表單的Top屬性為0,就是將視窗上邊沿緊靠頂部 setLocation(left, 0); } else if (top > -5 && top < 5 && !(isPtInRect(rect, point))) { // 當表單的上邊框與螢幕的頂端的距離小於5時 , // 並且滑鼠不再表單上 將QQ表單隱藏到螢幕的頂端 setLocation(left, 5 - height); } } /** * 判斷一個點是否在一個矩形內 * * @param rect:Rectangle對象 * @param point:Point對象 * @return:如果在矩形內返回true,不在或者對象為null則返回false */ public boolean isPtInRect(Rectangle rect, Point point) { if (rect != null && point != null) { int x0 = rect.x; int y0 = rect.y; int x1 = rect.width; int y1 = rect.height; int x = point.x; int y = point.y; return x >= x0 && x < x1 && y >= y0 && y < y1; } return false; } public static void main(String[] args) { MyFrame frame = new MyFrame(); frame.setTitle("Test"); frame.setSize(400, 300); frame.setLocation(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}