如何在Java中创建Windows通知

时间:2015-12-28 08:40:11

标签: java notifications

在Windows 10中,屏幕右下方会显示一条通知,我觉得它们非常有用。

有没有办法在Java中创建Windows通知?这就是他们的样子:

sample of windows notification desired

3 个答案:

答案 0 :(得分:42)

我可以使用这个非常简单的示例代码成功生成此结果:

screenshot

import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.net.MalformedURLException;

public class TrayIconDemo {

    public static void main(String[] args) throws AWTException, MalformedURLException {
        if (SystemTray.isSupported()) {
            TrayIconDemo td = new TrayIconDemo();
            td.displayTray();
        } else {
            System.err.println("System tray not supported!");
        }
    }

    public void displayTray() throws AWTException, MalformedURLException {
        //Obtain only one instance of the SystemTray object
        SystemTray tray = SystemTray.getSystemTray();

        //If the icon is a file
        Image image = Toolkit.getDefaultToolkit().createImage("icon.png");
        //Alternative (if the icon is on the classpath):
        //Image image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("icon.png"));

        TrayIcon trayIcon = new TrayIcon(image, "Tray Demo");
        //Let the system resize the image if needed
        trayIcon.setImageAutoSize(true);
        //Set tooltip text for the tray icon
        trayIcon.setToolTip("System tray icon demo");
        tray.add(trayIcon);

        trayIcon.displayMessage("Hello, World", "notification demo", MessageType.INFO);
    }
}

答案 1 :(得分:4)

这可以通过SystemTrayTrayIcon类来实现。此外,如果这是一个新的API,您可能需要查看专用教程" How to Use the System Tray"。

答案 2 :(得分:0)

使用 Toolkit.getDefaultToolkit(),正确答案适用于jdk 1.8 而不是Toolkit.getToolkit()