开发者

Programmatically close Java Tray Balloon

I am using java.awt.SystemTray to create and manage the tray icon and balloon messages. Everything works fine.

But I would like to know whether it is possible to close or fade the message after it i开发者_运维技巧s displayed.

Right now, the user needs to click the balloon or close it, otherwise the message will not go away.


I'm not sure about other platforms, but on Windows, the message will only disappear if the machine is in use - i.e. if the user is typing something or moving the mouse. If you don't move the mouse or type anything, the message will stay where it is.

The following code shows a message for me. If I move the mouse, it disappears about 5 seconds later. If I don't, it stays around until such time as I move the mouse or type something, at which point it disappears.

final TrayIcon ti = new TrayIcon(XTPSkin.getInstance().getAppIcon().getImage());
final SystemTray st = SystemTray.getSystemTray();
st.add(ti);
ti.displayMessage("foo", "bar", MessageType.INFO);

There's no direct way to remove the message before its time is up - however, you can remove the TrayIcon (and if necessary immediately re-add it, although this really isn't recommended). Removing the TrayIcon causes the message to also be removed.

The following code, added to the above, causes the TrayIcon and the message to both be removed:

SwingUtilities.invokeLater(new Runnable(){
    public void run() {
        try {
            Thread.sleep(1000); // Don't do this
            st.remove(ti);
        } catch (InterruptedException ie) {
            // You won't need this when the sleep is removed
        }
    }
});

Notes:

  • You need to wrap the first block of code above with some exception handling for AWTException
  • The Thread.sleep in the second block is strictly for demonstration purposes. Since this code will execute on the AWT thread, you should not include that sleep in actual code.
  • Continually removing and re-adding the TrayIcon in this way is probably a bad idea. Since the message does disappear if the user is using the machine, it's probably wisest not to do this.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜