Santosh Linkha Santosh Linkha - 2 months ago 13
Java Question

how to set icon for JFrame window and tray

I would like to show my own icon instead of the Java cup in the window.

screenshot of JFrame

Also when minimized, I would like to display, my own image. How will I be able to do so?

And where should I position my image relative to the source file?

[UPDATE]

I tried but no luck

TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().createImage("image/accounting.gif"));

//setIconImage();

SystemTray tray = SystemTray.getSystemTray();

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


Also i tried

TrayIcon trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));


But seriously doubt
createImage(
and even if it is Object don't know what to import.

Regards,

eee eee
Answer

Regarding your TrayIcon issue, you can refer below for a solution:

public static void createSystemTrayIcon() {

    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();
        Image image = Toolkit.getDefaultToolkit().getImage(
            System.getenv("MY_PROGRAM_HOME") + "game.ico"
        );

        PopupMenu popup = new PopupMenu();

        final MenuItem menuExit = new MenuItem("Quit");

        MouseListener mouseListener =
            new MouseListener() {
                public void mouseClicked(MouseEvent e) {}
                public void mouseEntered(MouseEvent e) {}
                public void mouseExited(MouseEvent e) {}
                public void mousePressed(MouseEvent e) {}
                public void mouseReleased(MouseEvent e) {}
        };

        ActionListener exitListener =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Runtime r = Runtime.getRuntime();
                    System.out.println("Exiting...");
                    r.exit(0);
                }
            };

        menuExit.addActionListener(exitListener);
        popup.add(menuExit);

        final TrayIcon trayIcon = new TrayIcon(image, "My program", popup);

        ActionListener actionListener =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    trayIcon.displayMessage(
                        "My program ",
                        "version: blahblah",
                        TrayIcon.MessageType.INFO
                    );
            }
        };

        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(actionListener);
        trayIcon.addMouseListener(mouseListener);

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

    } else {
        //  System Tray is not supported
    }
}