2011-11-21 24 views
6

我想創建一個JFrame實例並點擊它的minimize button,我想將它隱藏到System Tray這通常是windows的taskbar如何捕獲窗口最小化事件?

我會知道,通過使用SystemTrayjava.awt包我可以這樣做,但我既沒有得到任何教程,也沒有任何工作的程序示例。

我在這裏問這個問題要麼獲得鏈接到教程網站SystemTray類,或者如果任何機構知道如何陷阱窗口最小化事件,一個工作的例子。

+2

也許這兩個鏈接將幫助http://download.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html和http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/ – HRgiger

回答

4

這將捕獲窗口最小化事件,並將創建一個托盤圖標。它也會從任務欄中刪除窗口,它會在托盤圖標上添加一個偵聽器,這樣鼠標點擊就可以恢復窗口。該代碼是有點零碎,但應足夠好了你的學習目的:

public class Qwe extends JFrame { 

public static void main(String[] args) { 
    final Qwe qwe = new Qwe(); 

    qwe.addWindowStateListener(new WindowStateListener() { 
     public void windowStateChanged(WindowEvent e) { 
      if (e.getNewState() == ICONIFIED) { 
       try { 
        final TrayIcon trayIcon = new TrayIcon(new ImageIcon("/usr/share/icons/gnome/16x16/emotes/face-plain.png").getImage()); 
        trayIcon.addMouseListener(new MouseAdapter() { 
         @Override 
         public void mouseClicked(MouseEvent e) { 
          qwe.setVisible(true); 
          SystemTray.getSystemTray().remove(trayIcon); 
         } 
        }); 
        SystemTray.getSystemTray().add(trayIcon); 
        qwe.setVisible(false); 
       } catch (AWTException e1) { 
        e1.printStackTrace(); 
       } 
      } 
     } 
    }); 
    qwe.setSize(200, 200); 
    qwe.setVisible(true); 
} 

} 
5

WindowListener接口和JFrameaddWindowListener()方法應該可以幫助您確定何時框架已經被最小化。

+0

+1,更清潔.... –

2

將創造最好的辦法如下

1)SystemTray

2)添加JPopopMenuSystemTray's Icon

3)設置DefaultCloseOperationTopLevelContainer(在你的情況下爲JFrame

  • 使用WindowListenersetDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  • 在其他情況下

    總是工作setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

  • 通知不要忘記申報System.exit(1)SystemTray's JpopupMenu,從JMenuItem或其他Action/Event,因爲在這種形式currenet JVM永遠也不會消失從Native OS直到PC斷電或重啓

+0

感謝您的步驟明智的解釋。 –

0
frame.addWindowListener(new WindowAdapter() {@Override 
    public void windowIconified(WindowEvent e) {} 
});