Example usage for java.awt TrayIcon TrayIcon

List of usage examples for java.awt TrayIcon TrayIcon

Introduction

In this page you can find the example usage for java.awt TrayIcon TrayIcon.

Prototype

public TrayIcon(Image image, String tooltip) 

Source Link

Document

Creates a TrayIcon with the specified image and tooltip text.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    if (!SystemTray.isSupported()) {
        return;//from  ww  w  . java2s.co  m
    }
    SystemTray tray = SystemTray.getSystemTray();

    Dimension size = tray.getTrayIconSize();
    BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();

    g.setColor(Color.blue);
    g.fillRect(0, 0, size.width, size.height);

    PopupMenu popup = new PopupMenu();
    MenuItem miExit = new MenuItem("Exit");
    ActionListener al;
    al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
    miExit.addActionListener(al);
    popup.add(miExit);

    TrayIcon ti = new TrayIcon(bi, "System Tray Demo #2");
    ti.setPopupMenu(popup);

    al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getActionCommand());
        }
    };
    ti.setActionCommand("My Icon");
    ti.addActionListener(al);

    MouseListener ml = new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            System.out.println("Tray icon: Mouse clicked");
        }

        public void mouseEntered(MouseEvent e) {
            System.out.println("Tray icon: Mouse entered");
        }

        public void mouseExited(MouseEvent e) {
            System.out.println("Tray icon: Mouse exited");
        }

        public void mousePressed(MouseEvent e) {
            System.out.println("Tray icon: Mouse pressed");
        }

        public void mouseReleased(MouseEvent e) {
            System.out.println("Tray icon: Mouse released");
        }
    };
    ti.addMouseListener(ml);
    MouseMotionListener mml = new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
            System.out.println("Tray icon: Mouse dragged");
        }

        public void mouseMoved(MouseEvent e) {
            System.out.println("Tray icon: Mouse moved");
        }
    };
    ti.addMouseMotionListener(mml);

    MouseMotionListener[] mouseMotionListeners = ti.getMouseMotionListeners();
    for (MouseMotionListener ac : mouseMotionListeners) {
        ti.removeMouseMotionListener(ac);
    }

    tray.add(ti);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    if (!SystemTray.isSupported()) {
        return;//  w w w .  j  ava2 s .co m
    }
    SystemTray tray = SystemTray.getSystemTray();

    Dimension size = tray.getTrayIconSize();
    BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();

    g.setColor(Color.blue);
    g.fillRect(0, 0, size.width, size.height);

    PopupMenu popup = new PopupMenu();
    MenuItem miExit = new MenuItem("Exit");
    ActionListener al;
    al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
    miExit.addActionListener(al);
    popup.add(miExit);

    TrayIcon ti = new TrayIcon(bi, "System Tray Demo #2");
    ti.setPopupMenu(popup);

    al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getActionCommand());
        }
    };
    ti.setActionCommand("My Icon");
    ti.addActionListener(al);

    MouseListener ml = new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            System.out.println("Tray icon: Mouse clicked");
        }

        public void mouseEntered(MouseEvent e) {
            System.out.println("Tray icon: Mouse entered");
        }

        public void mouseExited(MouseEvent e) {
            System.out.println("Tray icon: Mouse exited");
        }

        public void mousePressed(MouseEvent e) {
            System.out.println("Tray icon: Mouse pressed");
        }

        public void mouseReleased(MouseEvent e) {
            System.out.println("Tray icon: Mouse released");
        }
    };
    ti.addMouseListener(ml);
    MouseMotionListener mml = new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
            System.out.println("Tray icon: Mouse dragged");
        }

        public void mouseMoved(MouseEvent e) {
            System.out.println("Tray icon: Mouse moved");
        }
    };
    ti.addMouseMotionListener(mml);

    Image image = ti.getImage();

    tray.add(ti);
}

From source file:com.ethercamp.harmony.desktop.HarmonyDesktop.java

private void start() throws Exception {
    log.info("Starting...");

    final TrayIcon trayIcon = new TrayIcon(new ImageIcon(imageDisabledUrl).getImage(), "Ethereum Harmony");
    trayIcon.setImageAutoSize(true); // Auto-size icon base on space

    // doesn't work
    //        Runtime.getRuntime().addShutdownHook(new Thread(() -> closeContext()));

    executor.submit(() -> {//from  ww  w  .ja v  a  2  s . c o  m
        try {
            context = new SpringApplicationBuilder(Application.class).headless(true).web(true).run();
            serverPort = Integer.valueOf(context.getEnvironment().getProperty("local.server.port"));
            log.info("Spring context created at port " + serverPort);
            trayIcon.setImage(new ImageIcon(imageEnabledUrl).getImage());
            setTrayMenu(trayIcon, browserMenu, logsMenu, quitMenu);
            openBrowser();

        } catch (Exception e) {
            final Throwable cause = DesktopUtil.findCauseFromSpringException(e);
            showErrorWindow(cause.getMessage(),
                    "Problem running Harmony:\n\n" + ExceptionUtils.getStackTrace(cause));
        }
    });

    if (!SystemTray.isSupported()) {
        log.error("System tray is not supported");
        return;
    }

    browserMenu.addActionListener(e -> openBrowser());
    quitMenu.addActionListener(event -> {
        log.info("Quit action was requested from tray menu");
        trayIcon.setImage(new ImageIcon(imageDisabledUrl).getImage());
        setTrayMenu(trayIcon, logsMenu, quitingMenu);
        closeContext();
        System.exit(0);
    });

    logsMenu.addActionListener(event -> {
        log.info("Logs action was requested from tray menu");
        final File logsFile = new File(LOGS_PATH);
        try {
            Desktop.getDesktop().open(logsFile);
        } catch (IOException e) {
            log.error("Problem opening logs dir", e);
        }
    });

    setTrayMenu(trayIcon, loadingMenu, logsMenu, quitMenu);
}

From source file:iqq.app.ui.manager.MainManager.java

public void enableTray() {
    if (SystemTray.isSupported() && tray == null) {
        menu = new PopupMenu();
        MenuItem restore = new MenuItem("  ?  ");
        restore.addActionListener(new ActionListener() {
            @Override/*from ww  w .  ja va  2s .c o m*/
            public void actionPerformed(ActionEvent e) {
                show();
            }
        });
        MenuItem exit = new MenuItem("  ?  ");
        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        menu.add(restore);
        menu.addSeparator();
        menu.add(exit);

        if (SystemUtils.isMac()) {
            defaultImage = skinService.getIconByKey("window/titleWIconBlack").getImage();
        } else {
            defaultImage = mainFrame.getIconImage();
        }
        blankImage = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
        tray = SystemTray.getSystemTray();
        icon = new TrayIcon(defaultImage, "IQQ");
        icon.setImageAutoSize(true);
        if (!SystemUtils.isMac()) {
            icon.setPopupMenu(menu);
        }
        try {
            tray.add(icon);
            icon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    logger.debug("MouseEvent " + e.getButton() + " " + e.getClickCount());
                    //??
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        if (flashOwner != null) {
                            Map<String, Object> data = (Map<String, Object>) flashOwner.getAttachment();
                            if (data != null && data.containsKey("action")
                                    && data.get("action").equals("ADD_BUDDY_REQUEST")) {
                                IMContext.getBean(FrameManager.class).showGetFriendRequest((IMBuddy) flashOwner,
                                        data.get("buddy_request_id").toString());
                                eventService.broadcast(new UIEvent(UIEventType.FLASH_USER_STOP, flashOwner));
                                return;
                            } else {
                                // ?
                                chatManager.addChat(flashOwner);
                            }
                        } else {
                            show();
                        }
                    }
                }
            });
        } catch (AWTException e) {
            logger.error("SystemTray add icon.", e);
        }
    }

}

From source file:com.raddle.tools.ClipboardTransferMain.java

public ClipboardTransferMain() {
    super();// w  w w.ja v a2s  .  c om
    initGUI();
    //// ??
    Properties p = new Properties();
    File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
    if (pf.exists()) {
        try {
            p.load(new FileInputStream(pf));
            serverAddrTxt.setText(StringUtils.defaultString(p.getProperty("server.addr")));
            portTxt.setText(StringUtils.defaultString(p.getProperty("local.port")));
            modifyClipChk.setSelected("true".equals(p.getProperty("allow.modify.local.clip")));
            autoChk.setSelected("true".equals(p.getProperty("auto.modify.remote.clip")));
        } catch (Exception e) {
            updateMessage(e.getMessage());
        }
    }
    m.addListener(new ClipboardListener() {

        @Override
        public void contentChanged(Clipboard clipboard) {
            setRemoteClipboard(false);
        }
    });
    m.setEnabled(autoChk.isSelected());
    //
    try {
        pasteImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_paste.png"));
        grayImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_gray.png"));
        sendImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/mail-send.png"));
        BufferedImage taskImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/taskbar.png"));
        setIconImage(taskImage);
        SystemTray systemTray = SystemTray.getSystemTray();
        trayIcon = new TrayIcon(grayImage, "??");
        systemTray.add(trayIcon);
        ////
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {// ???
                    if (ClipboardTransferMain.this.isVisible()) {
                        ClipboardTransferMain.this.setState(ICONIFIED);
                    } else {
                        ClipboardTransferMain.this.setVisible(true);
                        ClipboardTransferMain.this.setState(NORMAL);
                    }
                }
            }
        });
        ////// event 
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowIconified(WindowEvent e) {
                ClipboardTransferMain.this.setVisible(false);
                super.windowIconified(e);
            }

            @Override
            public void windowClosing(WindowEvent e) {
                File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
                pf.getParentFile().mkdirs();
                try {
                    Properties op = new Properties();
                    op.setProperty("server.addr", serverAddrTxt.getText());
                    op.setProperty("local.port", portTxt.getText());
                    op.setProperty("allow.modify.local.clip", modifyClipChk.isSelected() + "");
                    op.setProperty("auto.modify.remote.clip", autoChk.isSelected() + "");
                    FileOutputStream os = new FileOutputStream(pf);
                    op.store(os, "clip-trans");
                    os.flush();
                    os.close();
                } catch (Exception e1) {
                }
                shutdown();
                super.windowClosing(e);
            }
        });
    } catch (Exception e) {
        updateMessage(e.getMessage());
    }
    Thread thread = new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    String poll = iconQueue.take();
                    if ("send".equals(poll)) {
                        trayIcon.setImage(grayImage);
                    } else if ("paste".equals(poll)) {
                        Thread.sleep(20);
                        trayIcon.setImage(grayImage);
                    }
                } catch (InterruptedException e1) {
                    return;
                }
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:org.exist.launcher.Launcher.java

private boolean initSystemTray() {
    final Dimension iconDim = tray.getTrayIconSize();
    BufferedImage image = null;/* ww  w  .j av  a  2 s.  c  om*/
    try {
        image = ImageIO.read(getClass().getResource("icon32.png"));
    } catch (final IOException e) {
        showMessageAndExit("Launcher failed", "Failed to read system tray icon.", false);
    }
    trayIcon = new TrayIcon(image.getScaledInstance(iconDim.width, iconDim.height, Image.SCALE_SMOOTH),
            "eXist-db Launcher");

    final JDialog hiddenFrame = new JDialog();
    hiddenFrame.setUndecorated(true);
    hiddenFrame.setIconImage(image);

    final PopupMenu popup = createMenu();
    trayIcon.setPopupMenu(popup);
    trayIcon.addActionListener(actionEvent -> {
        trayIcon.displayMessage(null, "Right click for menu", TrayIcon.MessageType.INFO);
        setServiceState();
    });

    // add listener for left click on system tray icon. doesn't work well on linux though.
    if (!SystemUtils.IS_OS_LINUX) {
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                if (mouseEvent.getButton() == MouseEvent.BUTTON1) {
                    setServiceState();
                    hiddenFrame.add(popup);
                    popup.show(hiddenFrame, mouseEvent.getXOnScreen(), mouseEvent.getYOnScreen());
                }
            }
        });
    }

    try {
        hiddenFrame.setResizable(false);
        hiddenFrame.pack();
        hiddenFrame.setVisible(true);
        tray.add(trayIcon);
    } catch (final AWTException e) {
        return false;
    }

    return true;
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {/*from ww w. j av  a  2 s .  c  om*/
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}

From source file:org.kontalk.view.View.java

final void setTray() {
    if (!Config.getInstance().getBoolean(Config.MAIN_TRAY)) {
        this.removeTray();
        return;//ww w .  j a v  a 2 s. c o m
    }

    if (!SystemTray.isSupported()) {
        LOGGER.info("tray icon not supported");
        return;
    }

    if (mTrayIcon != null)
        // already set
        return;

    // load image
    Image image = getImage("kontalk.png");
    //image = image.getScaledInstance(22, 22, Image.SCALE_SMOOTH);

    // popup menu outside of frame, officially not supported
    final WebPopupMenu popup = new WebPopupMenu("Kontalk");
    WebMenuItem quitItem = new WebMenuItem(Tr.tr("Quit"));
    quitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            View.this.callShutDown();
        }
    });
    popup.add(quitItem);

    // workaround: menu does not disappear when focus is lost
    final WebDialog hiddenDialog = new WebDialog();
    hiddenDialog.setUndecorated(true);

    // create an action listener to listen for default action executed on the tray icon
    MouseListener listener = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            // menu must be shown on mouse release
            //check(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1)
                mMainFrame.toggleState();
            else
                check(e);
        }

        private void check(MouseEvent e) {
            //                if (!e.isPopupTrigger())
            //                    return;

            hiddenDialog.setVisible(true);

            // TODO ugly code
            popup.setLocation(e.getX() - 20, e.getY() - 40);
            popup.setInvoker(hiddenDialog);
            popup.setCornerWidth(0);
            popup.setVisible(true);
        }
    };

    mTrayIcon = new TrayIcon(image, "Kontalk" /*, popup*/);
    mTrayIcon.setImageAutoSize(true);
    mTrayIcon.addMouseListener(listener);

    SystemTray tray = SystemTray.getSystemTray();
    try {
        tray.add(mTrayIcon);
    } catch (AWTException ex) {
        LOGGER.log(Level.WARNING, "can't add tray icon", ex);
    }
}

From source file:org.shelloid.vpt.agent.App.java

private void setupSystemTray() {
    if (SystemTray.isSupported()) {
        try {//from w w w  .j  a va  2s.co  m
            final ConfigForm configForm = new ConfigForm(false);
            final PopupMenu popup = new PopupMenu();
            final TrayIcon trayIcon = new TrayIcon(createImage("/images/logo.jpg"), "Shelloid VPT Agent");
            tray = SystemTray.getSystemTray();
            MenuItem authenticateItem = new MenuItem("Configure Authentication");
            MenuItem aboutItem = new MenuItem("About Shelloid VPT Agent");
            MenuItem exitItem = new MenuItem("Exit");
            trayIcon.setPopupMenu(popup);
            tray.add(trayIcon);
            authenticateItem.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    configForm.setVisible(true);
                }
            });
            aboutItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null,
                            "Shelloid VPT Agent.\nVersion : " + getVersion()
                                    + "\n\n(c) 2014 Shelloid LLC. \nhttps://www.shelloid.com",
                            "Shelloid VPT Client", JOptionPane.INFORMATION_MESSAGE);
                }
            });
            exitItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Are you sure to exit Shelloid VPT Agent?",
                            "Shelloid VPT Agent", JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
                        shuttingDown = true;
                        closeAllConnections();
                        System.exit(0);
                    }
                }
            });
            popup.add(authenticateItem);
            popup.add(aboutItem);
            popup.addSeparator();
            popup.add(exitItem);
        } catch (Exception ex) {
            Platform.shelloidLogger.warn("System Tray Error: ", ex);
        }
    } else {
        System.out.println("System tray is not supported");
    }
}

From source file:org.sleeksnap.ScreenSnapper.java

/**
 * Initialize the tray menu/*ww w  .jav a 2s  .c  om*/
 */
private void initializeTray() {
    // Add uploaders from the list we loaded earlier
    final PopupMenu tray = new PopupMenu();
    // Add the action menu
    tray.add(new ActionMenuItem(Language.getString("cropupload"), ScreenshotAction.CROP));
    tray.add(new ActionMenuItem(Language.getString("fullupload"), ScreenshotAction.FULL));

    if (Platform.isWindows() || Platform.isLinux()) {
        tray.add(new ActionMenuItem(Language.getString("activeupload"), ScreenshotAction.ACTIVE));
    }

    tray.addSeparator();

    tray.add(new ActionMenuItem(Language.getString("clipboardupload"), ScreenshotAction.CLIPBOARD));
    tray.add(new ActionMenuItem(Language.getString("fileupload"), ScreenshotAction.FILE));

    tray.addSeparator();

    final MenuItem settings = new MenuItem(Language.getString("options"));
    settings.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            if (!openSettings()) {
                icon.displayMessage(Language.getString("error"), Language.getString("optionsOpenError"),
                        TrayIcon.MessageType.ERROR);
            }
        }
    });
    tray.add(settings);

    final MenuItem exit = new MenuItem(Language.getString("exit"));
    exit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            shutdown();
        }
    });
    tray.add(exit);

    icon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(Resources.ICON),
            Application.NAME + " v" + Version.getVersionString());
    icon.setPopupMenu(tray);
    icon.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            if (lastUrl != null) {
                try {
                    Util.openURL(new URL(lastUrl));
                } catch (final Exception e1) {
                    showException(e1, "Unable to open URL");
                }
            }
        }
    });
    try {
        SystemTray.getSystemTray().add(icon);
    } catch (final AWTException e1) {
        this.showException(e1);
    }
}