Show Notification in Windows using Java

To show a notification in Windows using Java, you can utilize the SystemTray and TrayIcon classes available in the java.awt package.

To show notifications in windows :

SystemTray and TrayIcon Approach:

  • Check if the system tray is supported (SystemTray.isSupported()).
  • Create a TrayIcon object with an image and tooltip.
  • Add the TrayIcon to the system tray (SystemTray.add()).
  • Use TrayIcon.displayMesage() to show the notification.

JOptionPane Approach:

  • Use JOptionPane.showMessageDialog() to display a notification-like dialog box.
  • Specify the message, title, and message type (e.g., JOptionPane.INFORMATION_MESSAGE).

Using SystemTray and TrayIcon:

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

public class NotificationExample {

    public static void main(String[] args) {
        if (SystemTray.isSupported()) {
            NotificationExample notificationExample = new NotificationExample();
            notificationExample.displayNotification("Notification Title", "Notification Message");
        } else {
            System.out.println("SystemTray is not supported on this platform.");
        }
    }

    public void displayNotification(String title, String message) {
        SystemTray tray = SystemTray.getSystemTray();
        Image image = Toolkit.getDefaultToolkit().getImage("icon.png"); // Change "icon.png" to your icon file path
        TrayIcon trayIcon = new TrayIcon(image, "Notification");
        trayIcon.setImageAutoSize(true);

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }

        trayIcon.displayMessage(title, message, MessageType.INFO);
    }
}

Using JOptionPane:

import javax.swing.JOptionPane;

public class NotificationExample {

    public static void main(String[] args) {
        displayNotification("Notification Title", "Notification Message");
    }

    public static void displayNotification(String title, String message) {
        JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
    }
}

Output:

When you run the code:

  1. Using SystemTray and TrayIcon Approach:
    • You willsee a notification icon appear in the system tray (usually located in the bottom-right corner of the screen) with the specified title and message. Clicking on the icon should display a notification bubble with the message.
  2. Using JOptionPane Approach:
    • A dialog box should appear with the specified title and message content, resembling a notification.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top