简体   繁体   English

以编程方式关闭Java Tray Balloon

[英]Programmatically close Java Tray Balloon

I am using java.awt.SystemTray to create and manage the tray icon and balloon messages. 我正在使用java.awt.SystemTray来创建和管理托盘图标和气球消息。 Everything works fine. 一切正常。

But I would like to know whether it is possible to close or fade the message after it is 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 - ie if the user is typing something or moving the mouse. 我不确定其他平台,但在Windows上,如果机器正在使用中,消息将消失 - 即用户正在键入内容或移动鼠标。 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. 如果我移动鼠标,它会在5秒后消失。 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). 在时间结束之前没有直接的方法来删除消息 - 但是,您可以删除TrayIcon (如果需要,可以立即重新添加它,尽管不建议这样做)。 Removing the TrayIcon causes the message to also be removed. 删除TrayIcon会导致消息也被删除。

The following code, added to the above, causes the TrayIcon and the message to both be removed: 以上代码添加到上面,导致TrayIcon和消息都被删除:

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 您需要使用AWTException一些异常处理来包装上面的第一个代码块
  • The Thread.sleep in the second block is strictly for demonstration purposes. 第二个块中的Thread.sleep主要用于演示目的。 Since this code will execute on the AWT thread, you should not include that sleep in actual code. 由于此代码将在AWT线程上执行,因此不应在实际代码中包含该睡眠。
  • Continually removing and re-adding the TrayIcon in this way is probably a bad idea. 以这种方式不断删除和重新添加TrayIcon可能是一个坏主意。 Since the message does disappear if the user is using the machine, it's probably wisest not to do this. 由于如果用户正在使用机器,消息确实消失,那么最好不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM