Usman Riaz
Usman Riaz

Reputation: 3020

System Tray image not loading java

I have a program which when runs displays an icon in system tray. i am using the below code to display an icon in system tray area:

public static void showTrayIcon() {
        if (java.awt.SystemTray.isSupported()) {
            st = java.awt.SystemTray.getSystemTray();

             image = Toolkit.getDefaultToolkit().getImage(PongeeUtil.class.getClass().getResource("export.png"));



            ActionListener listener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null, "Hello");
                }
            };

            PopupMenu popup = new PopupMenu();

            MenuItem defaultItem = new MenuItem("sdf");
            defaultItem.addActionListener(listener);
            popup.add(defaultItem);

            trayIcon = new TrayIcon(image, "Tray Demo", popup);

            trayIcon.addActionListener(listener);
            try {
                st.add(trayIcon);

            } catch (AWTException e) {
                System.err.println(e);
            }
        } 
    }

When i call this method in my main() i got something in my system tray but icon is missing. i think image is not able to load. image is in the same package where my java files resides.

What am i doing wrong here ?

Upvotes: 0

Views: 950

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

image is in the same package where my java files are

If you take a look at the JavaDocs for Toolkit#getImage you will find that it says...

Returns an image which gets pixel data from the specified file

This is important. You should also know that getImage loads the physical image in a background thread, which means if it fails to load the image, it will do so silently...

Okay. The core problem is, once the image is placed within the context of the application (with the class files), it becomes, whats commonly known as, an embedded resource.

These resources can not be loaded via any means that requires access to a file on the file system.

Instead, you need to use Class#getResource or Class#getResourceAsStream to load them, for example

image = Toolkit.getDefaultToolkit().getImage(YourClass.class.getResource("/package/path/to/classes/export.png"));

Or more preferabbly...

BufferedImage img = ImageIO.read(YourClass.class.getResource("/package/path/to/classes/export.png"));
image = new ImageIcon(img);

ImageIO will throw an IOException when it can't load the image for some reason, which gives you more diagnostic information to fix problems

nb:

  • YourClass is you class which contains the showTrayIcon method...
  • /package/path/to/classes is the package name under which the image is stored...

Upvotes: 2

Related Questions