Example usage for java.awt TrayIcon setPopupMenu

List of usage examples for java.awt TrayIcon setPopupMenu

Introduction

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

Prototype

public void setPopupMenu(PopupMenu popup) 

Source Link

Document

Sets the popup menu for this TrayIcon .

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    if (!SystemTray.isSupported()) {
        return;/*from ww w. j  a v  a2  s  . c  om*/
    }
    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);

    MouseListener[] mouseListeners = ti.getMouseListeners();
    for (MouseListener ac : mouseListeners) {
        ti.removeMouseListener(ac);
    }

    tray.add(ti);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    if (!SystemTray.isSupported()) {
        return;/*from  w ww.j ava 2 s .c  o 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:com.ethercamp.harmony.desktop.HarmonyDesktop.java

private static void setTrayMenu(TrayIcon trayIcon, MenuItem... items) {
    if (!SystemTray.isSupported()) {
        log.error("System tray is not supported");
        return;/*from  ww  w .  j  a  v  a 2s .  c o m*/
    }
    final SystemTray systemTray = SystemTray.getSystemTray();

    final PopupMenu popupMenu = new PopupMenu();
    stream(items).forEach(i -> popupMenu.add(i));
    trayIcon.setPopupMenu(popupMenu);

    try {
        stream(systemTray.getTrayIcons()).forEach(t -> systemTray.remove(t));
        systemTray.add(trayIcon);
    } catch (AWTException e) {
        log.error("Problem set tray", e);
    }
}

From source file:misc.TrayIconDemo.java

private static void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        System.out.println("SystemTray is not supported");
        return;/*ww  w  .j ava 2  s.  c o  m*/
    }
    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    MenuItem aboutItem = new MenuItem("About");
    CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
    CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
    Menu displayMenu = new Menu("Display");
    MenuItem errorItem = new MenuItem("Error");
    MenuItem warningItem = new MenuItem("Warning");
    MenuItem infoItem = new MenuItem("Info");
    MenuItem noneItem = new MenuItem("None");
    MenuItem exitItem = new MenuItem("Exit");

    //Add components to popup menu
    popup.add(aboutItem);
    popup.addSeparator();
    popup.add(cb1);
    popup.add(cb2);
    popup.addSeparator();
    popup.add(displayMenu);
    displayMenu.add(errorItem);
    displayMenu.add(warningItem);
    displayMenu.add(infoItem);
    displayMenu.add(noneItem);
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);

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

    trayIcon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "This dialog box is run from the About menu item");
        }
    });

    cb1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb1Id = e.getStateChange();
            if (cb1Id == ItemEvent.SELECTED) {
                trayIcon.setImageAutoSize(true);
            } else {
                trayIcon.setImageAutoSize(false);
            }
        }
    });

    cb2.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb2Id = e.getStateChange();
            if (cb2Id == ItemEvent.SELECTED) {
                trayIcon.setToolTip("Sun TrayIcon");
            } else {
                trayIcon.setToolTip(null);
            }
        }
    });

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MenuItem item = (MenuItem) e.getSource();
            //TrayIcon.MessageType type = null;
            System.out.println(item.getLabel());
            if ("Error".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.ERROR;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message",
                        TrayIcon.MessageType.ERROR);

            } else if ("Warning".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.WARNING;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message",
                        TrayIcon.MessageType.WARNING);

            } else if ("Info".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.INFO;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message",
                        TrayIcon.MessageType.INFO);

            } else if ("None".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.NONE;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message",
                        TrayIcon.MessageType.NONE);
            }
        }
    };

    errorItem.addActionListener(listener);
    warningItem.addActionListener(listener);
    infoItem.addActionListener(listener);
    noneItem.addActionListener(listener);

    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tray.remove(trayIcon);
            System.exit(0);
        }
    });
}

From source file:MonitorSaurausRex.MainMenu.java

private static void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        System.out.println("SystemTray is not supported");
        return;//from   w  w  w.ja v  a 2 s  . c om
    }
    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("Logo.png", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();
    trayIcon.setImageAutoSize(true);
    // Create a popup menu components
    MenuItem aboutItem = new MenuItem("About");
    CheckboxMenuItem cb1 = new CheckboxMenuItem("Menu");
    CheckboxMenuItem cb2 = new CheckboxMenuItem("Quarantine!");
    Menu displayMenu = new Menu("Actions");
    MenuItem errorItem = new MenuItem("Cut Connections");
    MenuItem warningItem = new MenuItem("Send Reports");
    MenuItem infoItem = new MenuItem("Kill Processes");
    MenuItem exitItem = new MenuItem("Exit");

    //Add components to popup menu
    popup.add(aboutItem);
    popup.addSeparator();
    popup.add(cb1);
    popup.add(cb2);
    popup.addSeparator();
    popup.add(displayMenu);
    displayMenu.add(errorItem);
    displayMenu.add(warningItem);
    displayMenu.add(infoItem);
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);

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

    trayIcon.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "MonitorSaurausRex, Designed for sec203 group project. The program was designed to be piece of software to combat Ransomware"
                            + " in a corparate enviroment. The Project was created by Luke Barlow, Dayan Patel, Rob Shire and Sian Skiggs.");
        }
    });

    cb1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb1Id = e.getStateChange();
            trayIcon.setImageAutoSize(true);
            if (cb1Id == ItemEvent.SELECTED) {
                trayIcon.setImageAutoSize(true);
            } else {
                trayIcon.setImageAutoSize(true);
            }
        }
    });

    cb2.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            int cb2Id = e.getStateChange();
            if (cb2Id == ItemEvent.SELECTED) {
                trayIcon.setToolTip("Sun TrayIcon");
            } else {
                trayIcon.setToolTip(null);
            }
        }
    });

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MenuItem item = (MenuItem) e.getSource();
            //TrayIcon.MessageType type = null;
            System.out.println(item.getLabel());
            if ("Error".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.ERROR;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message",
                        TrayIcon.MessageType.ERROR);

            } else if ("Warning".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.WARNING;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message",
                        TrayIcon.MessageType.WARNING);

            } else if ("Info".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.INFO;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message",
                        TrayIcon.MessageType.INFO);

            } else if ("None".equals(item.getLabel())) {
                //type = TrayIcon.MessageType.NONE;
                trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message",
                        TrayIcon.MessageType.NONE);
            }
        }
    };

    errorItem.addActionListener(listener);
    warningItem.addActionListener(listener);
    infoItem.addActionListener(listener);

    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tray.remove(trayIcon);
            System.exit(0);
        }
    });
}

From source file:jatoo.app.App.java

public App(final String title) {

    this.title = title;

    ////w w  w.  j  a va  2  s. c o m
    // load properties

    properties = new AppProperties(new File(getWorkingDirectory(), "app.properties"));
    properties.loadSilently();

    //
    // resources

    texts = new ResourcesTexts(getClass(), new ResourcesTexts(App.class));
    images = new ResourcesImages(getClass(), new ResourcesImages(App.class));

    //
    // create & initialize the window

    if (isDialog()) {

        window = new JDialog((Frame) null, getTitle());

        if (isUndecorated()) {
            ((JDialog) window).setUndecorated(true);
            ((JDialog) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JDialog) window).setResizable(isResizable());
    }

    else {

        window = new JFrame(getTitle());

        if (isUndecorated()) {
            ((JFrame) window).setUndecorated(true);
            ((JFrame) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JFrame) window).setResizable(isResizable());
    }

    window.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(final WindowEvent e) {
            System.exit(0);
        }

        @Override
        public void windowIconified(final WindowEvent e) {
            if (isHideWhenMinimized()) {
                hide();
            }
        }
    });

    //
    // set icon images
    // is either all icons from initializer package
    // or all icons from app package

    List<Image> windowIconImages = new ArrayList<>();
    String[] windowIconImagesNames = new String[] { "016", "020", "022", "024", "032", "048", "064", "128",
            "256", "512" };

    for (String size : windowIconImagesNames) {
        try {
            windowIconImages.add(new ImageIcon(getClass().getResource("app-icon-" + size + ".png")).getImage());
        } catch (Exception e) {
        }
    }

    if (windowIconImages.size() == 0) {

        for (String size : windowIconImagesNames) {
            try {
                windowIconImages
                        .add(new ImageIcon(App.class.getResource("app-icon-" + size + ".png")).getImage());
            } catch (Exception e) {
            }
        }
    }

    window.setIconImages(windowIconImages);

    //
    // this is the place for to call init method
    // after all local components are created
    // from now (after init) is only configuration

    init();

    //
    // set content pane ( and ansure transparency )

    JComponent contentPane = getContentPane();
    contentPane.setOpaque(false);

    ((RootPaneContainer) window).setContentPane(contentPane);

    //
    // pack the window right after the set of the content pane

    window.pack();

    //
    // center window (as default in case restore fails)
    // and try to restore the last location

    window.setLocationRelativeTo(null);
    window.setLocation(properties.getLocation(window.getLocation()));

    if (!isUndecorated()) {

        if (properties.getLastUndecorated(isUndecorated()) == isUndecorated()) {

            if (isResizable() && isSizePersistent()) {

                final String currentLookAndFeel = String.valueOf(UIManager.getLookAndFeel());

                if (properties.getLastLookAndFeel(currentLookAndFeel).equals(currentLookAndFeel)) {
                    window.setSize(properties.getSize(window.getSize()));
                }
            }
        }
    }

    //
    // fix location if out of screen

    Rectangle intersection = window.getGraphicsConfiguration().getBounds().intersection(window.getBounds());

    if ((intersection.width < window.getWidth() * 1 / 2)
            || (intersection.height < window.getHeight() * 1 / 2)) {
        UIUtils.setWindowLocationRelativeToScreen(window);
    }

    //
    // restore some properties

    setAlwaysOnTop(properties.isAlwaysOnTop());
    setHideWhenMinimized(properties.isHideWhenMinimized());
    setTransparency(properties.getTransparency(transparency));

    //
    // null is also a good value for margins glue gaps (is [0,0,0,0])

    Insets marginsGlueGaps = getMarginsGlueGaps();
    if (marginsGlueGaps == null) {
        marginsGlueGaps = new Insets(0, 0, 0, 0);
    }

    //
    // glue to margins on Ctrl + ARROWS

    if (isGlueToMarginsOnCtrlArrows()) {

        UIUtils.setActionForCtrlDownKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginBottom(window, marginsGlueGaps.bottom));
        UIUtils.setActionForCtrlLeftKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginLeft(window, marginsGlueGaps.left));
        UIUtils.setActionForCtrlRightKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginRight(window, marginsGlueGaps.right));
        UIUtils.setActionForCtrlUpKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginTop(window, marginsGlueGaps.top));
    }

    //
    // drag to move ( when provided component is not null )

    JComponent dragToMoveComponent = getDragToMoveComponent();

    if (dragToMoveComponent != null) {

        //
        // move the window by dragging the UI component

        int marginsGlueRange = Math.min(window.getGraphicsConfiguration().getBounds().width,
                window.getGraphicsConfiguration().getBounds().height);
        marginsGlueRange /= 60;
        marginsGlueRange = Math.max(marginsGlueRange, 15);

        UIUtils.forwardDragAsMove(dragToMoveComponent, window, marginsGlueRange, marginsGlueGaps);

        //
        // window popup

        dragToMoveComponent.addMouseListener(new MouseAdapter() {
            public void mouseReleased(final MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    windowPopup = getWindowPopup(e.getLocationOnScreen());
                    windowPopup.setVisible(true);
                }
            }
        });

        //
        // always dispose the popup when window lose the focus

        window.addFocusListener(new FocusAdapter() {
            public void focusLost(final FocusEvent e) {
                if (windowPopup != null) {
                    windowPopup.setVisible(false);
                    windowPopup = null;
                }
            }
        });
    }

    //
    // tray icon

    if (hasTrayIcon()) {

        if (SystemTray.isSupported()) {

            Image trayIconImage = windowIconImages.get(0);
            Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize();

            for (Image windowIconImage : windowIconImages) {

                if (Math.abs(trayIconSize.width - windowIconImage.getWidth(null)) < Math
                        .abs(trayIconImage.getWidth(null) - windowIconImage.getWidth(null))) {
                    trayIconImage = windowIconImage;
                }
            }

            final TrayIcon trayIcon = new TrayIcon(trayIconImage);
            trayIcon.setPopupMenu(getTrayIconPopup());

            trayIcon.addMouseListener(new MouseAdapter() {
                public void mouseClicked(final MouseEvent e) {

                    if (SwingUtilities.isLeftMouseButton(e)) {
                        if (e.getClickCount() >= 2) {
                            if (window.isVisible()) {
                                hide();
                            } else {
                                show();
                            }
                        }
                    }
                }
            });

            try {
                SystemTray.getSystemTray().add(trayIcon);
            } catch (AWTException e) {
                logger.error(
                        "unexpected exception trying to add the tray icon ( the desktop system tray is missing? )",
                        e);
            }
        }

        else {
            logger.error("the system tray is not supported on the current platform");
        }
    }

    //
    // hidden or not

    if (properties.isVisible()) {
        window.setVisible(true);
    }

    //
    // close the splash screen
    // if there is one

    try {

        SplashScreen splash = SplashScreen.getSplashScreen();

        if (splash != null) {
            splash.close();
        }
    }

    catch (UnsupportedOperationException e) {
        getLogger().info("splash screen not supported", e);
    }

    //
    // add shutdown hook for #destroy()

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            App.this.destroy();
        }
    });

    //
    // after init

    afterInit();
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private void addSystemTrayIcon() {
    if (!SystemTray.isSupported())
        return;//from w ww.jav  a2s  . c  o  m

    TrayIcon icon = new TrayIcon(this.icon.getImage());
    icon.setPopupMenu(getTrayIconPopup());
    icon.setToolTip("EntrainerFX");

    try {
        SystemTray.getSystemTray().add(icon);
    } catch (AWTException e) {
        GuiUtil.handleProblem(e);
    }
}

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 www .j av  a2s  .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:com.jsystem.j2autoit.AutoItAgent.java

private static void createAndShowGUI() {
    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        Log.error("SystemTray is not supported\n");
        return;/*from w w w.j ava  2s  .  c  o m*/
    }
    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("images/jsystem_ico.gif", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    final MenuItem aboutItem = new MenuItem("About");
    final MenuItem startAgentItem = new MenuItem("Start J2AutoIt Agent");
    final MenuItem stopAgentItem = new MenuItem("Stop J2AutoIt Agent");
    final MenuItem exitItem = new MenuItem("Exit");
    final MenuItem changePortItem = new MenuItem("Setting J2AutoIt Port");
    final MenuItem deleteTemporaryFilesItem = new MenuItem("Delete J2AutoIt Script");
    final MenuItem temporaryHistoryFilesItem = new MenuItem("History Size");
    final MenuItem displayLogFile = new MenuItem("Log");
    final MenuItem forceShutDownTimeOutItem = new MenuItem("Force ShutDown TimeOut");
    final MenuItem writeConfigurationToFile = new MenuItem("Save Configuration To File");
    final CheckboxMenuItem debugModeItem = new CheckboxMenuItem("Debug Mode", isDebug);
    final CheckboxMenuItem forceAutoItShutDownItem = new CheckboxMenuItem("Force AutoIt Script ShutDown",
            isForceAutoItShutDown);
    final CheckboxMenuItem autoDeleteHistoryItem = new CheckboxMenuItem("Auto Delete History",
            isAutoDeleteFiles);
    final CheckboxMenuItem useAutoScreenShot = new CheckboxMenuItem("Auto Screenshot", isUseScreenShot);

    //Add components to popup menu
    popup.add(aboutItem);
    popup.add(writeConfigurationToFile);
    popup.addSeparator();
    popup.add(forceAutoItShutDownItem);
    popup.add(forceShutDownTimeOutItem);
    popup.addSeparator();
    popup.add(debugModeItem);
    popup.add(displayLogFile);
    popup.add(useAutoScreenShot);
    popup.addSeparator();
    popup.add(autoDeleteHistoryItem);
    popup.add(deleteTemporaryFilesItem);
    popup.add(temporaryHistoryFilesItem);
    popup.addSeparator();
    popup.add(changePortItem);
    popup.addSeparator();
    popup.add(startAgentItem);
    popup.add(stopAgentItem);
    popup.addSeparator();
    popup.add(exitItem);

    trayIcon.setToolTip("J2AutoIt Agent");
    trayIcon.setImageAutoSize(true);
    trayIcon.setPopupMenu(popup);
    final DisplayLogFile displayLog = new DisplayLogFile();
    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        Log.error("TrayIcon could not be added.\n");
        return;
    }

    trayIcon.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            startAgentItem.setEnabled(!serverState);
            stopAgentItem.setEnabled(serverState);
            deleteTemporaryFilesItem.setEnabled(isDebug && HistoryFile.containEntries());
            autoDeleteHistoryItem.setEnabled(isDebug);
            temporaryHistoryFilesItem.setEnabled(isDebug && isAutoDeleteFiles);
            displayLogFile.setEnabled(isDebug);
            forceShutDownTimeOutItem.setEnabled(isForceAutoItShutDown);
        }

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

    writeConfigurationToFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            AutoItProperties.DEBUG_MODE_KEY.setValue(isDebug.toString());
            AutoItProperties.AUTO_DELETE_TEMPORARY_SCRIPT_FILE_KEY.setValue(isAutoDeleteFiles.toString());
            AutoItProperties.AUTO_IT_SCRIPT_HISTORY_SIZE_KEY.setValue(DEFAULT_HistorySize.toString());
            AutoItProperties.FORCE_AUTO_IT_PROCESS_SHUTDOWN_KEY.setValue(isForceAutoItShutDown.toString());
            AutoItProperties.AGENT_PORT_KEY.setValue(webServicePort.toString());
            AutoItProperties.SERVER_UP_ON_INIT_KEY.setValue(serverState.toString());
            if (!AutoItProperties.savePropertiesFileSafely()) {
                Log.error("Fail to save properties file");
            }
        }
    });

    debugModeItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isDebug = (e.getStateChange() == ItemEvent.SELECTED);
            deleteTemporaryFilesItem.setEnabled(isDebug && HistoryFile.containEntries());
            Log.infoLog("Keeping the temp file is " + (isDebug ? "en" : "dis") + "able\n");
            trayIcon.displayMessage((isDebug ? "Debug" : "Normal") + " Mode",
                    "The system will " + (isDebug ? "not " : "") + "delete \nthe temporary autoIt scripts."
                            + (isDebug ? "\nSee log file for more info." : ""),
                    MessageType.INFO);
        }
    });

    useAutoScreenShot.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isUseScreenShot = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog("Auto screenshot is " + (isUseScreenShot ? "" : "in") + "active\n");
        }
    });

    forceAutoItShutDownItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isForceAutoItShutDown = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog((isForceAutoItShutDown ? "Force" : "Soft") + " AutoIt Script ShutDown\n");
            trayIcon.displayMessage("AutoIt Script Termination",
                    (isForceAutoItShutDown ? "Hard shutdown" : "Soft shutdown"), MessageType.INFO);
        }
    });

    autoDeleteHistoryItem.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            isAutoDeleteFiles = (e.getStateChange() == ItemEvent.SELECTED);
            Log.infoLog((isAutoDeleteFiles ? "Auto" : "Manual") + " AutoIt Script Deletion\n");
            trayIcon.displayMessage("AutoIt Script Deletion", (isAutoDeleteFiles ? "Auto" : "Manual") + " Mode",
                    MessageType.INFO);
            if (isAutoDeleteFiles) {
                HistoryFile.init();
            } else {
                HistoryFile.close();
            }
        }
    });

    forceShutDownTimeOutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String timeOutAsString = JOptionPane.showInputDialog(
                    "Please Insert Force ShutDown TimeOut (in seconds)",
                    String.valueOf(shutDownTimeOut / 1000));
            try {
                shutDownTimeOut = 1000 * Long.parseLong(timeOutAsString);
            } catch (Exception e2) {
            }
            Log.infoLog("Setting the force shutdown time out to : " + (shutDownTimeOut / 1000) + " seconds.\n");
        }
    });

    displayLogFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                displayLog.reBuild(Log.getCurrentLogs());
                displayLog.actionPerformed(actionEvent);
            } catch (Exception e2) {
            }
        }
    });

    temporaryHistoryFilesItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String historySize = JOptionPane.showInputDialog("Please Insert History AutoIt Script Files",
                    String.valueOf(HistoryFile.getHistory_Size()));
            try {
                int temp = Integer.parseInt(historySize);
                if (temp > 0) {
                    if (HistoryFile.getHistory_Size() != temp) {
                        HistoryFile.setHistory_Size(temp);
                        Log.infoLog("The history files size is " + historySize + NEW_LINE);
                    }
                } else {
                    Log.warning("Illegal History Size: " + historySize + NEW_LINE);
                }
            } catch (Exception exception) {
                Log.throwableLog(exception.getMessage(), exception);
            }
        }
    });

    deleteTemporaryFilesItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HistoryFile.forceDeleteAll();
        }
    });

    startAgentItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            runWebServer();
        }
    });

    stopAgentItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            shutDownWebServer();
        }
    });

    aboutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            JOptionPane.showMessageDialog(null, "J2AutoIt Agent By JSystem And Aqua Software");
        }
    });

    changePortItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String portAsString = JOptionPane.showInputDialog("Please Insert new Port",
                    String.valueOf(webServicePort));
            if (portAsString != null) {
                try {
                    int temp = Integer.parseInt(portAsString);
                    if (temp > 1000) {
                        if (temp != webServicePort) {
                            webServicePort = temp;
                            shutDownWebServer();
                            startAutoItWebServer(webServicePort);
                            runWebServer();
                        }
                    } else {
                        Log.warning("Port number should be greater then 1000\n");
                    }
                } catch (Exception exception) {
                    Log.error("Illegal port number\n");
                    return;
                }
            }
        }
    });

    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            tray.remove(trayIcon);
            shutDownWebServer();
            Log.info("Exiting from J2AutoIt Agent\n");
            System.exit(0);
        }
    });
}

From source file:org.kootox.episodesmanager.ui.systray.EpisodesTrayIcon.java

public void create() {

    //Check the SystemTray support
    if (!SystemTray.isSupported()) {
        if (log.isInfoEnabled()) {
            log.info("SystemTray is not supported");
        }/*ww w .j  av a 2s  .co m*/
        return;
    }

    if (loaded) {
        return;
    }

    final PopupMenu popup = new PopupMenu();
    final TrayIcon trayIcon = new TrayIcon(createImage("systray.png", "tray icon"));
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    MenuItem display = new MenuItem("Display");
    MenuItem exit = new MenuItem("Exit");

    //Add components to popup menu
    popup.add(display);
    popup.addSeparator();
    popup.add(exit);

    trayIcon.setPopupMenu(popup);

    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        if (log.isDebugEnabled()) {
            log.debug("TrayIcon could not be added.");
        }
        return;
    }

    trayIcon.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent mouseEvent) {
            if (mouseEvent.getButton() == MouseEvent.BUTTON1) {
                showHide();
            }
        }

        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            //Do nothing
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent) {
            //Do nothing
        }

        @Override
        public void mouseEntered(MouseEvent mouseEvent) {
            //Do nothing
        }

        @Override
        public void mouseExited(MouseEvent mouseEvent) {
            //Do nothing
        }
    });

    display.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showHide();
        }
    });

    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            EpisodesManagerMainUI mainUI = EpisodesManagerContext.MAIN_UI_ENTRY_DEF.getContextValue(context);
            mainUI.close();
        }
    });

    loaded = true;
    if (log.isDebugEnabled()) {
        log.debug("Systray loaded");
    }
}