轉載:JFrame 建立系統托盤中的圖標

import java.awt.AWTException;  import java.awt.Image;  import java.awt.MenuItem;  import java.awt.PopupMenu;  import java.awt.SystemTray;  import java.awt.Toolkit;  import java.awt.TrayIcon;  import java.awt.event.ActionEvent;  import java.awt.event.ActionListener;    import javax.swing.JFrame;      public class MySystemTray extends JFrame{            public MySystemTray() {          init();      }            public void init() {                    this.setSize(300, 200);          this.setLocationRelativeTo(null);          this.setTray();          this.setVisible(true);      }            //添加托盤顯示:1.先判斷當前平臺是否支持托盤顯示      public void setTray() {                    if(SystemTray.isSupported()){//判斷當前平臺是否支持托盤功能              //建立托盤實例              SystemTray tray = SystemTray.getSystemTray();              //建立托盤圖標:1.顯示圖標Image 2.停留提示text 3.彈出菜單popupMenu 4.建立托盤圖標實例              //1.建立Image圖像              Image image = Toolkit.getDefaultToolkit().getImage("trayIconImage/clientIcon.jpg");              //2.停留提示text              String text = "MySystemTray";              //3.彈出菜單popupMenu              PopupMenu popMenu = new PopupMenu();              MenuItem itmOpen = new MenuItem("打開");              itmOpen.addActionListener(new ActionListener(){                  public void actionPerformed(ActionEvent e) {                      Show();                  }                             });              MenuItem itmHide = new MenuItem("隱藏");              itmHide.addActionListener(new ActionListener(){                  public void actionPerformed(ActionEvent e) {                      UnVisible();                  }              });              MenuItem itmExit = new MenuItem("退出");              itmExit.addActionListener(new ActionListener(){                  public void actionPerformed(ActionEvent e) {                      Exit();                  }              });              popMenu.add(itmOpen);              popMenu.add(itmHide);              popMenu.add(itmExit);                            //建立托盤圖標              TrayIcon trayIcon = new TrayIcon(image,text,popMenu);              //將托盤圖標加到托盤上              try {                  tray.add(trayIcon);              } catch (AWTException e1) {                  e1.printStackTrace();              }          }      }            //內部類中不能直接調用外部類(this不能指向)      public void UnVisible() {          this.setVisible(false);      }      public void Show() {          this.setVisible(true);      }      public void Exit() {          System.exit(0);      }                  public static void main(String[] args) {          new MySystemTray();      }  } 
相關文章
相關標籤/搜索