如何在Java中生成Windows通知

14ifxucb  于 2022-12-21  发布在  Java
关注(0)|答案(3)|浏览(197)

在Windows 10中有一个通知,在屏幕右下方打开,我发现它们相当有用。
有没有办法在Java中创建Windows通知?下面是它们的外观:

knsnq2tg

knsnq2tg1#

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

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

public class TrayIconDemo {

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

    public void displayTray() throws AWTException {
        //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);
    }
}
llmtgqce

llmtgqce2#

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

gstyhher

gstyhher3#

您可以通过通知类java.lang.Object org.controlsfx.control轻松地使用javafx通知

public static showNotification(String title,String text){
Notifications notificationTest=Notifications.create();
notificationTest.position(Pos.BASELINE_RIGHT);
notificationTest.title(title);
notificationTest.text(text);
notificationTest.show();//for error noti notificationTest.showError();

}

https://www.javadoc.io/static/org.controlsfx/controlsfx/8.40.16/org/controlsfx/control/Notifications.html

相关问题