我们在使用QQ的时候,可以通过向好友发送一个窗口抖动,然后就可以看到窗口在不段的跳舞了,呵呵。其实,我们在java中也可以实现这样的效果,其原理就是不断的在小范围内随机改变窗口的location就可以实现了。代码如下:
final int amplitude = 6; // 抖动的幅度
final long _times = 3 * 1000; // 抖动的时间
final Point location = shell.getLocation(); // 记录最开始时shell的位置
final long startTime = System.currentTimeMillis();
new Thread() {
public void run() {
int startX = location.x - amplitude/2, startY = location.y - amplitude/2;
while (System.currentTimeMillis() - startTime <= _times) {
final int rx = RandomUtil.random(startX, startX + amplitude);
final int ry = RandomUtil.random(startY, startY + amplitude);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
shell.setLocation(rx, ry);
}
});
Thread.yield();
}
// restore the shell's location
shell.getDisplay().syncExec(new Runnable() {
public void run() {
shell.setLocation(location);
}
});
}
}.start();
代码中抖动的幅度是指以窗口的左上角顶点为中心左右的偏移距离(取值为一半),比如一个窗口的location为(20,30),那么对于6个像素的振幅,其location可以活动的范围就是一个矩形[(17,27),(27,23),(17,33),(23,33)]。
其中RandomUtil为一实用类,来获取某一个范围内的随机数,其代码如下:
public class RandomUtil {
private static final Random random = new Random();
/**
* return a integer value between from and to.
* @param from start value,include
* @param to end value,exclude
* @return
*/
public static int random(int from, int to) {
return from + random.nextInt(to - from);
}
}
另外,使用Thread.yield()和Thread.sleep(interval)是不太一样的,前者是交出CPU运行时间,但并不表示下一个CPU时间就不是分配给该线程;而后者则是完全交出CPU运行时间,直到睡眠结束。所以分别实用这两个来暂停线程所看到的效果将不太一样,呵呵,具体是什么样的效果,大家自己试试吧:-)