如何将应用程序添加到系统托盘

时间:2012-03-14 12:19:52

标签: java swing icons awt system-tray

我希望在窗口关闭时将我的应用程序添加到系统托盘(类似于Google Talk应用程序)。然后,当我单击系统托盘中的“开”图标时,应用程序窗口将再次变为活动状态。我怎么能用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);
      }
   }
});

2 个答案:

答案 0 :(得分:3)

您已正确设置DefaultCloseOperations

myFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)

此代码行与myFrame.setVisible(false)相同,然后将JFrameJPopupMenu恢复为仅调用myFrame.setVisible(true)

答案 1 :(得分:2)

我得到了答案。现在,当我关闭窗口关闭时,当我点击系统托盘图标然后它再次打开我的窗口

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