Search code examples
javaswingiconsawtsystem-tray

How to add application to System Tray


I want to add my application to the system tray when it's window is closed (similar to the Google Talk application). And then when I click the on icon in the system tray the application window becomes active again. How can I do this in Java?

final SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("images.jpg");
final TrayIcon trayIcon = new TrayIcon(image);
try {
   SystemTray.getSystemTray().add(trayIcon);
} catch (AWTException e2) {
   e2.printStackTrace();
}

this.addWindowStateListener(new WindowStateListener() {
   public void windowStateChanged(WindowEvent e) {
      if (e.getNewState() == EXIT_ON_CLOSE) {

         trayIcon.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
               setVisible(true);
            }
         });
         setVisible(false);
      }
   }
});

Solution

  • you have set DefaultCloseOperations correctly

    myFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
    

    this code line is same as myFrame.setVisible(false), then for restore of JFrame from JPopupMenu to call only myFrame.setVisible(true)