简体   繁体   中英

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);
      }
   }
});

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)

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);
                    }
                });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM