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:com.ln.gui.Main.java

@SuppressWarnings("unchecked")
public Main() {//from  w  w w . j  a v a2s .  c  o m
    System.gc();
    setIconImage(Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln6464.png"));
    DateFormat dd = new SimpleDateFormat("dd");
    DateFormat dh = new SimpleDateFormat("HH");
    DateFormat dm = new SimpleDateFormat("mm");
    Date day = new Date();
    Date hour = new Date();
    Date minute = new Date();
    dayd = Integer.parseInt(dd.format(day));
    hourh = Integer.parseInt(dh.format(hour));
    minutem = Integer.parseInt(dm.format(minute));
    setTitle("Liquid Notify Revision 2");
    Description.setBackground(Color.WHITE);
    Description.setContentType("text/html");
    Description.setEditable(false);
    Getcalendar.Main();
    HyperlinkListener hyperlinkListener = new ActivatedHyperlinkListener(f, Description);
    Description.addHyperlinkListener(hyperlinkListener);
    //Add components
    setContentPane(contentPane);
    setJMenuBar(menuBar);
    contentPane.setLayout(
            new MigLayout("", "[220px:230.00:220,grow][209.00px:n:5000,grow]", "[22px][][199.00,grow][grow]"));
    eventsbtn.setToolTipText("Displays events currently set to notify");
    eventsbtn.setMinimumSize(new Dimension(220, 23));
    eventsbtn.setMaximumSize(new Dimension(220, 23));
    contentPane.add(eventsbtn, "cell 0 0");
    NewsArea.setBackground(Color.WHITE);
    NewsArea.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.DARK_GRAY,
            Color.DARK_GRAY));
    NewsArea.setMinimumSize(new Dimension(20, 22));
    NewsArea.setMaximumSize(new Dimension(10000, 22));
    contentPane.add(NewsArea, "cell 1 0,growx,aligny top");
    menuBar.add(File);
    JMenuItem Settings = new JMenuItem("Settings");
    Settings.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\settings.png"));
    Settings.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Settings setup = new Settings();
            setup.setVisible(true);
            setup.setLocationRelativeTo(rootPane);
        }
    });
    File.add(Settings);
    File.add(mntmNewMenuItem);
    Tray.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\ln1616.png"));
    File.add(Tray);
    Exit.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\exit.png"));
    File.add(Exit);

    menuBar.add(mnNewMenu);

    Update.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\update.png"));
    Update.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                URL localURL = new URL("http://jiiks.net23.net/tlnotify/online.html");
                URLConnection localURLConnection = localURL.openConnection();
                BufferedReader localBufferedReader = new BufferedReader(
                        new InputStreamReader(localURLConnection.getInputStream()));
                String str = localBufferedReader.readLine();
                if (!str.contains("YES")) {
                    String st2221 = "Updates server appears to be offline";
                    JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                            JOptionPane.DEFAULT_OPTION);
                    JDialog dialog1 = pane1.createDialog("Update");
                    dialog1.setLocationRelativeTo(null);
                    dialog1.setVisible(true);
                    dialog1.setAlwaysOnTop(true);
                } else if (str.contains("YES")) {
                    URL localURL2 = new URL("http://jiiks.net23.net/tlnotify/latestversion.html");
                    URLConnection localURLConnection1 = localURL2.openConnection();
                    BufferedReader localBufferedReader2 = new BufferedReader(
                            new InputStreamReader(localURLConnection1.getInputStream()));
                    String str2 = localBufferedReader2.readLine();
                    Updatechecker.latestver = str2;
                    if (Integer.parseInt(str2) <= Configuration.version) {
                        String st2221 = "No updates available =(";
                        JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                                JOptionPane.DEFAULT_OPTION);
                        JDialog dialog1 = pane1.createDialog("Update");
                        dialog1.setLocationRelativeTo(null);
                        dialog1.setVisible(true);
                        dialog1.setAlwaysOnTop(true);
                    } else if (Integer.parseInt(str2) > Configuration.version) {
                        String st2221 = "Updates available!";
                        JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                                JOptionPane.DEFAULT_OPTION);
                        JDialog dialog1 = pane1.createDialog("Update");
                        dialog1.setLocationRelativeTo(null);
                        dialog1.setVisible(true);
                        dialog1.setAlwaysOnTop(true);

                        Updatechecker upd = new Updatechecker();
                        upd.setVisible(true);
                        upd.setLocationRelativeTo(rootPane);
                        upd.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                    }
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    });
    mnNewMenu.add(Update);
    JMenuItem About = new JMenuItem("About");
    About.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\about.png"));
    About.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            About a = new About();
            a.setVisible(true);
            a.setLocationRelativeTo(rootPane);
            a.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        }
    });
    mnNewMenu.add(About);
    JMenuItem Github = new JMenuItem("Github");
    Github.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\github.png"));
    Github.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String url = "https://github.com/Jiiks/Liquid-Notify-Rev2";
            try {
                java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
    mnNewMenu.add(Github);
    JMenuItem Thread = new JMenuItem("Thread");
    Thread.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\liquid.png"));
    Thread.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String url = "http://www.teamliquid.net/forum/viewmessage.php?topic_id=318184";
            try {
                java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
    mnNewMenu.add(Thread);
    Refreshbtn.setToolTipText("Refreshes calendar, please don't spam ^_^");
    Refreshbtn.setPreferredSize(new Dimension(90, 20));
    Refreshbtn.setMinimumSize(new Dimension(100, 20));
    Refreshbtn.setMaximumSize(new Dimension(100, 20));
    contentPane.add(Refreshbtn, "flowx,cell 0 1,alignx left");
    //Components to secondary panel   
    Titlebox = new JComboBox();
    contentPane.add(Titlebox, "cell 1 1,growx,aligny top");
    Titlebox.setMinimumSize(new Dimension(20, 20));
    Titlebox.setMaximumSize(new Dimension(10000, 20));
    //Set other
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 686, 342);
    contentPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
    NewsArea.setEnabled(false);
    NewsArea.setEditable(false);
    NewsArea.setText("News: " + News);
    contentPane.add(panel, "cell 0 2,grow");
    panel.setLayout(null);
    final JCalendar calendar = new JCalendar();
    calendar.getMonthChooser().setPreferredSize(new Dimension(120, 20));
    calendar.getMonthChooser().setMinimumSize(new Dimension(120, 24));
    calendar.getYearChooser().setLocation(new Point(20, 0));
    calendar.getYearChooser().setMaximum(100);
    calendar.getYearChooser().setMaximumSize(new Dimension(100, 2147483647));
    calendar.getYearChooser().setMinimumSize(new Dimension(50, 20));
    calendar.getYearChooser().setPreferredSize(new Dimension(50, 20));
    calendar.getYearChooser().getSpinner().setPreferredSize(new Dimension(100, 20));
    calendar.getYearChooser().getSpinner().setMinimumSize(new Dimension(100, 20));
    calendar.getMonthChooser().getSpinner().setPreferredSize(new Dimension(119, 20));
    calendar.getMonthChooser().getSpinner().setMinimumSize(new Dimension(120, 24));
    calendar.getDayChooser().getDayPanel().setFont(new Font("Tahoma", Font.PLAIN, 11));
    calendar.setDecorationBordersVisible(true);
    calendar.setTodayButtonVisible(true);
    calendar.setBackground(Color.LIGHT_GRAY);
    calendar.setBounds(0, 0, 220, 199);
    calendar.getDate();
    calendar.setWeekOfYearVisible(false);
    calendar.setDecorationBackgroundVisible(false);
    calendar.setMaxDayCharacters(2);
    calendar.getDayChooser().setFont(new Font("Tahoma", Font.PLAIN, 10));
    panel.add(calendar);
    Descriptionscrollpane.setLocation(new Point(100, 100));
    Descriptionscrollpane.setMaximumSize(new Dimension(10000, 10000));
    Descriptionscrollpane.setMinimumSize(new Dimension(20, 200));
    Description.setLocation(new Point(100, 100));
    Description.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY,
            Color.DARK_GRAY, Color.DARK_GRAY));
    Description.setMaximumSize(new Dimension(1000, 400));
    Description.setMinimumSize(new Dimension(400, 200));
    contentPane.add(Descriptionscrollpane, "cell 1 2 1 2,growx,aligny top");
    Descriptionscrollpane.setViewportView(Description);
    verticalStrut.setMinimumSize(new Dimension(12, 20));
    contentPane.add(verticalStrut, "cell 0 1");
    Notify.setToolTipText("Adds selected event to notify event list.");
    Notify.setHorizontalTextPosition(SwingConstants.CENTER);
    Notify.setPreferredSize(new Dimension(100, 20));
    Notify.setMinimumSize(new Dimension(100, 20));
    Notify.setMaximumSize(new Dimension(100, 20));
    contentPane.add(Notify, "cell 0 1,alignx right");
    calendar.getMonthChooser().addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            month = calendar.getMonthChooser().getMonth();
            Parser.parse();
        }
    });

    calendar.getDayChooser().addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            try {
                int h = calendar.getMonthChooser().getMonth();
                @SuppressWarnings("deprecation")
                int date = calendar.getDate().getDate();
                int month = calendar.getMonthChooser().getMonth() + 1;
                globmonth = calendar.getMonthChooser().getMonth();
                sdate = date;
                datestring = Integer.toString(sdate);
                monthstring = Integer.toString(month);
                String[] Hours = Betaparser.Hours;
                String[] Titles = Betaparser.STitle;
                String[] Full = new String[Hours.length];
                String[] Minutes = Betaparser.Minutes;
                String[] Des = Betaparser.Description;
                String[] Des2 = new String[Betaparser.Description.length];
                String Seconds = "00";
                String gg;
                int[] IntHours = new int[Hours.length];
                int[] IntMins = new int[Hours.length];
                int Events = 0;
                monthday = monthstring + "|" + datestring + "|";
                Titlebox.removeAllItems();
                for (int a = 0; a != Hours.length; a++) {
                    IntHours[a] = Integer.parseInt(Hours[a]);
                    IntMins[a] = Integer.parseInt(Minutes[a]);
                }
                for (int i1 = 0; i1 != Hours.length; i1++) {
                    if (Betaparser.Events[i1].startsWith(monthday)) {
                        Full[i1] = String.format("%02d:%02d", IntHours[i1], IntMins[i1]) + " | " + Titles[i1];
                        Titlebox.addItem(Full[i1]);
                    }
                }
            } catch (Exception e1) {
                //Catching mainly due to boot property change            
            }
        }
    });
    Image image = Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln1616.png");
    final SystemTray tray = SystemTray.getSystemTray();
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setVisible(true);
        }
    };
    PopupMenu popup = new PopupMenu();
    MenuItem defaultItem = new MenuItem();
    defaultItem.addActionListener(listener);
    TrayIcon trayIcon = null;
    trayIcon = new TrayIcon(image, "LiquidNotify Revision 2", popup);

    trayIcon.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            setVisible(true);
        }
    });//
    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        System.err.println(e);
    }
    if (trayIcon != null) {
        trayIcon.setImage(image);
    }

    Tray.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });

    Titlebox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Descparser.parsedesc();
        }
    });

    Refreshbtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Getcalendar.Main();
            Descparser.parsedesc();
        }
    });

    Notify.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            NOTIFY = Descparser.TTT;
            NOTIFYD = Descparser.DDD;
            NOTIFYH = Descparser.HHH;
            NOTIFYM = Descparser.MMM;
            int i = events;
            NOA[i] = NOTIFY;
            NOD[i] = NOTIFYD;
            NOH[i] = NOTIFYH;
            NOM[i] = NOTIFYM;
            Eventlist[i] = "Starts in: " + Integer.toString(NOD[i]) + " Days " + Integer.toString(NOH[i])
                    + " Hours " + Integer.toString(NOM[i]) + " Minutes " + " | " + NOA[i];
            events = events + 1;
            Notifylist si = new Notifylist();
            si.setVisible(false);
            si.setBounds(1, 1, 1, 1);
            si.dispose();
            if (thread.getState().name().equals("PENDING")) {
                thread.execute();
            }
        }
    });
    eventsbtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Notifylist list = new Notifylist();
            if (played == 1) {
                asd.close();
                played = 0;
            }
            list.setVisible(true);
            list.setLocationRelativeTo(rootPane);
            list.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        }
    });

    mntmNewMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (thread.getState().name().equals("PENDING")) {
                thread.execute();
            }
            Userstreams us = new Userstreams();
            us.setVisible(true);
            us.setLocationRelativeTo(rootPane);
        }
    });

    Exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            //Absolute exit
            JOptionPane.showMessageDialog(rootPane, "Bye bye :(", "Exit", JOptionPane.INFORMATION_MESSAGE);
            Runtime ln = Runtime.getRuntime();
            ln.gc();
            final Frame[] allf = Frame.getFrames();
            final Window[] allw = Window.getWindows();
            for (final Window allwindows : allw) {
                allwindows.dispose();
            }
            for (final Frame allframes : allf) {
                allframes.dispose();
                System.exit(0);
            }
        }
    });
}

From source file:com.darkenedsky.reddit.traders.RedditTraders.java

/**
 * Construct a new RedditTraders instance.
 * //from w  w  w. ja v  a  2  s. co  m
 * 
 */
public RedditTraders() {

    // Load XML configuration file, connect to DB and connect to Reddit API
    try {
        config = new Configuration();
        addListener(new Help(this));
        addListener(new About(this));
        addListener(new Confirm(this));
        addListener(new Activate(this));
        listeners.put("DEACTIVATE", new Activate(this));
        addListener(new CountAllSubs(this));
        addListener(new ModHelp(this));
        addListener(new AcceptModInvite(this));
        addListener(new Install(this));
        addListener(new Cake(this));
        addListener(new Trade(this));
        addListener(new TopTraders(this, "TOP20", 20));
        addListener(new Lookup(this));
        addListener(new SetLegacy(this));
        addListener(new SetTextFlair(this));
        addListener(new ViewFlair(this));
        addListener(new Resolve(this));
        listeners.put("BLAME", new Resolve(this));
        listeners.put("CLOSE", new Resolve(this));
        addListener(new SetFlair(this));
        listeners.put("REMOVEFLAIR", new SetFlair(this));
        addListener(new SetModFlair(this));
        listeners.put("REMOVEMODFLAIR", new SetModFlair(this));
        addListener(new SetBlameBan(this));
        addListener(new SetList(this));
        listeners.put("SETHAVELIST", new SetList(this));
        addListener(new GetList(this));
        listeners.put("HAVELIST", new GetList(this));
        addListener(new SetAccountAgeRequirement(this));
        addListener(new SetVerifiedEmail(this));
        addListener(new Undo(this));
        addListener(new LastTrades(this, "LAST10", 10));
        addListener(new SetCheckBan(this));
        addListener(new SetDaysBetween(this));

        // Build a system tray icon
        SystemTray tray = SystemTray.getSystemTray();

        PopupMenu popup = new PopupMenu();

        MenuItem todaysLog = new MenuItem("Today's Log");
        todaysLog.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    new TextFrame("logs/RedditTraders.log").setVisible(true);
                } catch (Exception e1) {
                    LOG.error(e1);
                }
            }
        });
        popup.add(todaysLog);

        MenuItem exit = new MenuItem("Exit");
        ActionListener exitListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };
        exit.addActionListener(exitListener);
        popup.add(exit);

        Image image = Toolkit.getDefaultToolkit().getImage("reddit.png");
        TrayIcon trayIcon = new TrayIcon(image, "RedditTraders " + config.getVersion(), popup);
        trayIcon.setImageAutoSize(true);
        tray.add(trayIcon);

        LOG.debug("RedditTraders launched OK.");
    } catch (Exception x) {
        x.printStackTrace();
        System.exit(0);
    }
}

From source file:org.duracloud.syncui.SyncUIDriver.java

private static void createSysTray(final String url, final Server srv) {
    final TrayIcon trayIcon;
    try {//from  w  w  w  . j  a va  2s . co  m

        if (SystemTray.isSupported()) {

            SystemTray tray = SystemTray.getSystemTray();
            InputStream is = org.duracloud.syncui.SyncUIDriver.class.getClassLoader()
                    .getResourceAsStream("tray.png");

            Image image = ImageIO.read(is);
            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {
                    log.debug("Tray Icon - Mouse clicked!");
                }

                public void mouseEntered(MouseEvent e) {
                    log.debug("Tray Icon - Mouse entered!");
                }

                public void mouseExited(MouseEvent e) {
                    log.debug("Tray Icon - Mouse exited!");
                }

                public void mousePressed(MouseEvent e) {
                    log.debug("Tray Icon - Mouse pressed!");
                }

                public void mouseReleased(MouseEvent e) {
                    log.debug("Tray Icon - Mouse released!");
                }
            };

            ActionListener exitListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    log.info("Exiting...");
                    try {
                        srv.stop();
                        while (!srv.isStopped()) {
                            WaitUtil.wait(1);
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    System.exit(0);
                }
            };

            PopupMenu popup = new PopupMenu();
            MenuItem view = new MenuItem("View Status");
            view.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    launchBrowser(url);
                }
            });
            popup.add(view);

            MenuItem exit = new MenuItem("Exit");
            exit.addActionListener(exitListener);
            popup.add(exit);

            trayIcon = new TrayIcon(image, "DuraCloud Sync Tool", popup);

            ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    trayIcon.displayMessage("Action Event", "An Action Event Has Been Performed!",
                            TrayIcon.MessageType.INFO);
                }
            };

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

            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                log.error("TrayIcon could not be added.");
            }
        } else {
            log.warn("System Tray is not supported.");
        }

    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

}

From source file:edu.stanford.muse.launcher.Main.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", "Muse");
    try {//from ww  w . ja v  a  2 s .c om
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    TrayIcon trayIcon = null;
    if (SystemTray.isSupported()) {
        System.out.println("Adding Muse to the system tray");
        SystemTray tray = SystemTray.getSystemTray();

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

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

        ActionListener QuitMuseListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                out.println("*** Received quit from system tray. Stopping the Jetty embedded web server.");
                try {
                    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 Muse window");
        defaultItem.addActionListener(openMuseControlsListener);
        popup.add(defaultItem);
        MenuItem quitItem = new MenuItem("Quit Muse");
        quitItem.addActionListener(QuitMuseListener);
        popup.add(quitItem);

        /// ... add other items
        // construct a TrayIcon
        String message = "Muse 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 Muse 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) {
            System.err.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:ui.main.MainViewController.java

private void showNotifications(String chat, String message) {
    // a general method for view notifications -> windows notification
    if (!isnotifiable.isSelected()) {
        return;/* w ww. j a va  2  s .c om*/
    }
    URL url = System.class.getResource("/resources/LogoTransparent.png");
    java.awt.Image image = Toolkit.getDefaultToolkit().getImage(url);
    TrayIcon trayIcon = new TrayIcon(image, "Instant Messenger Plus");
    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();

        trayIcon.setImageAutoSize(true);
        try {
            tray.add(trayIcon);

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

        trayIcon.displayMessage("IMP: " + chat, message, TrayIcon.MessageType.INFO);
    }
}

From source file:edu.stanford.epadd.launcher.Main.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  w w . ja v  a  2 s. c  o  m*/
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

        URL u = Main.class.getClassLoader().getResource("muse-icon.png"); // note: this better be 16x16, Windows doesn't resize! Mac os does.
        System.out.println("ePADD icon resource is " + u);
        Image image = Toolkit.getDefaultToolkit().getImage(u);
        System.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 Jetty embedded web server.");
                try {
                    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) {
            System.err.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.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 . ja  v  a 2  s .  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:edu.stanford.muse.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 {//from  w w w .jav a  2  s . c om
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

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

        // create menu items and their listeners
        ActionListener openMuseControlsListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    launchBrowser(BASE_URL + "/info", null);
                } 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) {
            err.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:org.languagetool.gui.Main.java

private void hideToTray() {
    if (!isInTray) {
        SystemTray tray = SystemTray.getSystemTray();
        String iconPath = tray.getTrayIconSize().height > 16 ? TRAY_ICON : TRAY_SMALL_ICON;
        URL iconUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(iconPath);
        Image img = Toolkit.getDefaultToolkit().getImage(iconUrl);
        PopupMenu popup = makePopupMenu();
        try {//  w  w  w  .  j  ava  2  s.c om
            trayIcon = new TrayIcon(img, TRAY_TOOLTIP, popup);
            trayIcon.addMouseListener(new TrayActionListener());
            setTrayIcon();
            tray.add(trayIcon);
        } catch (AWTException e1) {
            Tools.showError(e1);
        }
    }
    isInTray = true;
    frame.setVisible(false);
}

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  w w  . j a v  a  2  s.c  om
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

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

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

        // create menu items and their listeners
        ActionListener openMuseControlsListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    launchBrowser(BASE_URL, null); // 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);
    }
    // ...
}