Java:Flash一个窗口来吸引用户的注意力

有没有更好的方法在Java中使用Flash来刷新窗口:

public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); } 

我知道这段代码很可怕……但它的工作正常。 (我应该实现一个循环…)

有两种常用方法:使用JNI在任务栏的窗口上设置紧急提示,并创建通知图标/消息。 我更喜欢第二种方式,因为它是跨平台的并且不那么烦人。

请参阅TrayIcon类的文档 ,尤其是displayMessage()方法。

以下链接可能会引起关注:

  • Java SE 6中的新系统托盘function
  • Java编程 – 图标化窗口闪烁
  • TrayIcon用于早期版本的Java

好吧,我们可以做一些小的改进。 ;)

我会使用Timer来确保调用者不必等待方法返回。 并且在给定窗口上一次防止多个闪存操作也会很好。

 import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import javax.swing.JFrame; public class WindowFlasher { private final Timer timer = new Timer(); private final Map flashing = new ConcurrentHashMap(); public void flashWindow(final JFrame window, final long period, final int blinks) { TimerTask newTask = new TimerTask() { private int remaining = blinks * 2; @Override public void run() { if (remaining-- > 0) window.setVisible(!window.isVisible()); else { window.setVisible(true); cancel(); } } @Override public boolean cancel() { flashing.remove(this); return super.cancel(); } }; TimerTask oldTask = flashing.put(window, newTask); // if the window is already flashing, cancel the old task if (oldTask != null) oldTask.cancel(); timer.schedule(newTask, 0, period); } }