Example #1
0
  private MainPanel(final JFrame frame) {
    super();
    add(check);
    setPreferredSize(new Dimension(320, 240));

    if (!SystemTray.isSupported()) {
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      return;
    }
    frame.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowIconified(WindowEvent e) {
            if (check.isSelected()) {
              e.getWindow().dispose();
            }
          }
        });
    // or
    // frame.addWindowStateListener(new WindowStateListener() {
    //    @Override public void windowStateChanged(WindowEvent e) {
    //        if (check.isSelected() && e.getNewState() == Frame.ICONIFIED) {
    //            e.getWindow().dispose();
    //        }
    //    }
    // });

    final SystemTray tray = SystemTray.getSystemTray();
    Dimension d = tray.getTrayIconSize();
    BufferedImage image = makeBufferedImage(new StarIcon(), d.width, d.height);
    final PopupMenu popup = new PopupMenu();
    final TrayIcon icon = new TrayIcon(image, "TRAY", popup);

    MenuItem item1 = new MenuItem("OPEN");
    item1.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            frame.setVisible(true);
          }
        });
    MenuItem item2 = new MenuItem("EXIT");
    item2.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            tray.remove(icon);
            frame.dispose();
            // frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
          }
        });
    popup.add(item1);
    popup.add(item2);

    try {
      tray.add(icon);
    } catch (AWTException e) {
      e.printStackTrace();
    }
  }
Example #2
0
  public void install() {
    try {
      if (trayIcon == null && SystemTray.isSupported()) {
        SystemTray systemTray = SystemTray.getSystemTray();
        Dimension size = systemTray.getTrayIconSize();
        trayIcon = createTrayIcon(size);
        systemTray.add(trayIcon);

        JPopupMenu popup = new JPopupMenu();
        trayIcon.setJPopupMenu(popup);
        createPopup(popup);
      }
    } catch (AWTException e) {
      e.printStackTrace();
    }
  }