Example usage for java.awt SystemTray add

List of usage examples for java.awt SystemTray add

Introduction

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

Prototype

public void add(TrayIcon trayIcon) throws AWTException 

Source Link

Document

Adds a TrayIcon to the SystemTray .

Usage

From source file:edu.stanford.epadd.launcher.Splash.java

/** we need a system tray icon for management.
 * http://docs.oracle.com/javase/6/docs/api/java/awt/SystemTray.html */
public static void setupSystemTrayIcon() {
    // Set the app name in the menu bar for mac. 
    // c.f. http://stackoverflow.com/questions/8918826/java-os-x-lion-set-application-name-doesnt-work
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "ePADD");
    try {//  w  ww  .  j  av  a  2  s  .  c om
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    TrayIcon trayIcon = null;
    if (SystemTray.isSupported()) {
        tellUser("Adding ePADD to the system tray");
        SystemTray tray = SystemTray.getSystemTray();

        URL u = ePADD.class.getClassLoader().getResource("muse-icon.png"); // note: this better be 16x16, Windows doesn't resize! Mac os does.
        out.println("ePADD icon resource is " + u);

        Image image = Toolkit.getDefaultToolkit().getImage(u);
        out.println("Image = " + image);

        // create menu items and their listeners
        ActionListener openMuseControlsListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    launchBrowser(BASE_URL); // no + "info" for epadd like in muse
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        };

        ActionListener QuitMuseListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                out.println("*** Received quit from system tray. Stopping the Tomcat embedded web server.");
                try {
                    shutdownSessions();
                    server.stop();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                System.exit(0); // we need to explicitly system.exit because we now use Swing (due to system tray, etc).
            }
        };

        // create a popup menu
        PopupMenu popup = new PopupMenu();
        MenuItem defaultItem = new MenuItem("Open ePADD window");
        defaultItem.addActionListener(openMuseControlsListener);
        popup.add(defaultItem);
        MenuItem quitItem = new MenuItem("Quit ePADD");
        quitItem.addActionListener(QuitMuseListener);
        popup.add(quitItem);

        /// ... add other items
        // construct a TrayIcon
        String message = "ePADD menu";
        // on windows - the tray menu is a little non-intuitive, needs a right click (plain click seems unused)
        if (System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0)
            message = "Right click for ePADD menu";
        trayIcon = new TrayIcon(image, message, popup);
        System.out.println("tray Icon = " + trayIcon);
        // set the TrayIcon properties
        //            trayIcon.addActionListener(openMuseControlsListener);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            out.println(e);
        }
        // ...
    } else {
        // disable tray option in your application or
        // perform other actions
        //            ...
    }
    System.out.println("Done!");
    // ...
    // some time later
    // the application state has changed - update the image
    if (trayIcon != null) {
        //        trayIcon.setImage(updatedImage);
    }
    // ...
}

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  w ww .  j  ava  2 s. c  o m*/
        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:application.Main.java

public void createTrayIcon(final Stage stage) {
    // if the operating system
    // supports the system tray
    if (SystemTray.isSupported()) {
        // get the SystemTray instance
        SystemTray tray = SystemTray.getSystemTray();
        // load an image
        java.awt.Image image = null;
        try {//from  w w  w  .  j av  a2s . c  o  m
            //                File file = new File(iconLocation);
            //                image = ImageIO.read(file);
            URL urlIcon = Main.class.getResource(iconLocation);
            image = ImageIO.read(urlIcon);
        } catch (IOException ex) {
            System.out.println(ex);
        }

        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                hide(stage);
            }
        });

        // create an action listener to listen for default action executed on the tray icon
        final ActionListener closeListener = new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        stage.close();
                        controller.terminate();
                        //                           // fileWatcher.setTerminateWatching(Boolean.TRUE);
                        System.out.println(applicationTitle + " terminated!");
                        Platform.exit();
                        System.exit(0);
                    }
                });
            }
        };

        ActionListener showListener = new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        stage.show();
                    }
                });
            }
        };

        // create a pop-up menu
        PopupMenu popupMenu = new PopupMenu();

        MenuItem nameItem = new MenuItem(applicationTitle);
        nameItem.addActionListener(showListener);
        popupMenu.add(nameItem);

        popupMenu.addSeparator();

        MenuItem showItem = new MenuItem("Show");
        showItem.addActionListener(showListener);
        popupMenu.add(showItem);

        MenuItem closeItem = new MenuItem("Close");
        closeItem.addActionListener(closeListener);
        popupMenu.add(closeItem);

        /// ... add other menu items

        // construct a TrayIcon, scaling the image to 16x16 (the default dimensions of a tray icon)
        trayIcon = new TrayIcon(image.getScaledInstance(24, 24, Image.SCALE_DEFAULT), applicationTitle,
                popupMenu);
        // set the TrayIcon properties
        trayIcon.addActionListener(showListener);

        // add the tray image
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.err.println(e);
        }
    }
}

From source file:vn.topmedia.monitor.form.MDIMain.java

public void goToTray() {
    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();
        normal = Toolkit.getDefaultToolkit().getImage("normal.gif");
        MouseListener mouseListener = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                //                    System.out.println("Tray Icon - Mouse clicked!");                 
            }//w  w w.  j a  v  a2  s .  c o m

            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!"); 
                showMonitor(0);
            }

            public void mouseReleased(MouseEvent e) {
                //                    System.out.println("Tray Icon - Mouse released!");                 
            }
        };

        ActionListener exitListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("Exiting...");
                mnuItmExit.doClick();
            }
        };

        ActionListener showMonitorListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                showMonitor(2);
            }
        };

        popup = new PopupMenu();
        //---------------------------            
        MenuItem showItem;
        showItem = new MenuItem("Show");
        showItem.addActionListener(showMonitorListener);
        popup.add(showItem);
        //-----------------            
        popup.addSeparator();
        //------------------------            
        MenuItem defaultItem = new MenuItem("Exit");
        defaultItem.addActionListener(exitListener);
        popup.add(defaultItem);
        //------------------------
        trayIcon = new TrayIcon(normal, "ExMonitor 1.3", popup);

        ActionListener actionListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                showMonitor(2);
            }
        };

        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
    }

}

From source file:org.yccheok.jstock.gui.MainFrame.java

private void createSystemTrayIcon() {
    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();
        final Image image;
        if (Utils.isWindows7() || Utils.isWindows8()) {
            image = new javax.swing.ImageIcon(getClass().getResource("/images/128x128/chart.png")).getImage();
        } else {/*from   ww w .ja v a 2s  .  com*/
            image = new javax.swing.ImageIcon(getClass().getResource("/images/16x16/chart.png")).getImage();
        }

        MouseListener mouseListener = new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    MainFrame.this.setVisible(true);
                    MainFrame.this.setState(Frame.NORMAL);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }
        };

        ActionListener exitListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MainFrame.this.setVisible(false);
                MainFrame.this.dispose();
            }
        };

        PopupMenu popup = new PopupMenu();
        MenuItem defaultItem = new MenuItem(
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/gui").getString("MainFrame_Exit"));
        defaultItem.addActionListener(exitListener);
        popup.add(defaultItem);

        trayIcon = new TrayIcon(image, GUIBundle.getString("MainFrame_Application_Title"), popup);

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        };

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

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            trayIcon = null;
            JOptionPane.showMessageDialog(MainFrame.this,
                    java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                            .getString("warning_message_trayicon_could_not_be_added"),
                    java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages").getString(
                            "warning_title_trayicon_could_not_be_added"),
                    JOptionPane.WARNING_MESSAGE);
        }

    } else {
        //  System Tray is not supported
        trayIcon = null;
        JOptionPane.showMessageDialog(MainFrame.this,
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                        .getString("warning_message_system_tray_is_not_supported"),
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                        .getString("warning_title_system_tray_is_not_supported"),
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:org.yccheok.jstock.gui.JStock.java

private void createSystemTrayIcon() {
    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();
        final Image image = new javax.swing.ImageIcon(getClass().getResource("/images/128x128/chart.png"))
                .getImage();//from   ww  w .j  a  v  a 2s.com

        MouseListener mouseListener = new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    JStock.this.setVisible(true);
                    JStock.this.setState(Frame.NORMAL);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }
        };

        ActionListener exitListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JStock.this.setVisible(false);
                JStock.this.dispose();
            }
        };

        PopupMenu popup = new PopupMenu();
        MenuItem defaultItem = new MenuItem(
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/gui").getString("MainFrame_Exit"));
        defaultItem.addActionListener(exitListener);
        popup.add(defaultItem);

        trayIcon = new TrayIcon(image, GUIBundle.getString("MainFrame_Application_Title"), popup);

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        };

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

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            trayIcon = null;
            JOptionPane.showMessageDialog(JStock.this,
                    java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                            .getString("warning_message_trayicon_could_not_be_added"),
                    java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages").getString(
                            "warning_title_trayicon_could_not_be_added"),
                    JOptionPane.WARNING_MESSAGE);
        }

    } else {
        //  System Tray is not supported
        trayIcon = null;
        JOptionPane.showMessageDialog(JStock.this,
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                        .getString("warning_message_system_tray_is_not_supported"),
                java.util.ResourceBundle.getBundle("org/yccheok/jstock/data/messages")
                        .getString("warning_title_system_tray_is_not_supported"),
                JOptionPane.WARNING_MESSAGE);
    }
}