Search code examples
javasystem-traytrayicon

System tray balloon message doesn't show up java


I want to make my system try icon to pop up a balloon message but it doesn't do that. This is the code. It should pop up if a simple if statement is fulfilled but nothing happens. The system tray icon is visible and when left clicking on it it shows menu.

package systemtray;

import java.awt.*;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Systemtray {

public static void main(String[] args) {

     TrayIcon trayIcon = null;
    if (SystemTray.isSupported()) {
        // get the SystemTray instance
        SystemTray tray = SystemTray.getSystemTray();
        // load an image
       Image image = Toolkit.getDefaultToolkit().getImage("D:/xxx/facebook.jpg");          
       // create a action listener to listen for default action executed on the tray icon
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // execute default action of the application
            }
         };

     // create a popup menu
     PopupMenu popup = new PopupMenu();
     //create menu item for the default action
     MenuItem defaultItem = new MenuItem("A menu item");
     defaultItem.addActionListener(listener);
     popup.add(defaultItem);
     /// ... add other items
     // construct a TrayIcon*/
    trayIcon = new TrayIcon(image, "Tray Demo", popup);


     int a = 0;
     int b = 1;
     if (a + b == 1){
     trayIcon.displayMessage("Message Title", 
        "Message Content",
        TrayIcon.MessageType.INFO);
     }
     // set the TrayIcon properties
     trayIcon.addActionListener(listener);
     // ...
     // add the tray image
     try {
         tray.add(trayIcon);
     } catch (AWTException e) {
         System.err.println(e);
     }
     // ...
 } else {
     // disable tray option in your application or
     // perform other actions
 }
 // ...
 // some time later
 // the application state has changed - update the image
// if (trayIcon != null) {
  //   trayIcon.setImage(updatedImage);
 //}
 // ...
}
}

Solution

  • You can't display the popup balloon unless the icon is shown. You have to show the icon first (which I assume is tray.add in your code).