2

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);
      }
   }
});
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Vinay
  • 347
  • 1
  • 7
  • 16
  • possible duplicate of [How do I put a Java app in the system tray?](http://stackoverflow.com/questions/758083/how-do-i-put-a-java-app-in-the-system-tray) – MByD Mar 14 '12 at 12:20

2 Answers2

3

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)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • thanks for this. but i am not using Popup to restore. i want when i click on icon in system tray it should open my Login window. – Vinay Mar 14 '12 at 12:38
  • 1
    then add [MouseListener to the Icon in the SystemTray](http://stackoverflow.com/a/8460383/714968) – mKorbel Mar 14 '12 at 13:49
2

I got answer. Now when i close window its closing and when i click on System tray icon then it again open my window

Image image = Toolkit.getDefaultToolkit().getImage("src/resources/ChatIcon1.jpeg");
    final TrayIcon trayIcon = new TrayIcon(image);
    trayIcon.setToolTip("OfficeCommunicator");
    try {
        SystemTray.getSystemTray().add(trayIcon);
    } catch (AWTException e2) {
        e2.printStackTrace();
    }


                trayIcon.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        trayIcon.displayMessage("hi", "You Opened Me Again", TrayIcon.MessageType.INFO);
                        setVisible(true);
                    }
                });
}
Vinay
  • 347
  • 1
  • 7
  • 16