【java SWT界面的托盘显示】

//点击关闭或者最小化时程序不会退出而是显示到托盘中    当然也可以是显示在任务栏中的

  public class TrayApp {

  public static void main(String[] args) {

  Display display = new Display();

  final Shell shell = new Shell(display);

  shell.setText("最小化到系統托盤");

  //取消系統中預設的圖標,預設圖標在托盤不能顯示

  shell.setImage(display.getSystemImage(SWT.ICON_INFORMATION));

  //構建系統托盤

  final Tray tray = display.getSystemTray();

  final TrayItem trayItem = new TrayItem(tray, SWT.NONE);

  //設置在托盤中顯示的程序圖標

  trayItem.setImage(display.getSystemImage(SWT.ICON_INFORMATION));

  //程序啟動時,窗口是顯示的,所以托盤圖標隱藏

  trayItem.setVisible(false);

  trayItem.setToolTipText(shell.getText());

  trayItem.addSelectionListener(new SelectionAdapter() {

  public void widgetSelected(SelectionEvent e) {

  toggleDisplay(shell, tray);

  }

  });

  final Menu trayMenu = new Menu(shell, SWT.POP_UP);

  MenuItem showMenuItem = new MenuItem(trayMenu, SWT.PUSH);

  showMenuItem.setText("顯示窗口(&s)");

  //顯示窗口,并隱藏托盤圖標

  showMenuItem.addSelectionListener(new SelectionAdapter() {

  public void widgetSelected(SelectionEvent e) {

  toggleDisplay(shell, tray);

  }

  });

  trayMenu.setDefaultItem(showMenuItem);

  new MenuItem(trayMenu, SWT.SEPARATOR);

  //托盤中的退出菜單,程式只能通過這個菜單退出

  MenuItem exitMenuItem = new MenuItem(trayMenu, SWT.PUSH);

  exitMenuItem.setText("退出程式(&x)");

  exitMenuItem.addSelectionListener(new SelectionAdapter() {

  public void widgetSelected(SelectionEvent event) {

  shell.dispose();

  }

  });

  //在托盤圖標點擊鼠標右鍵時的事件,彈出系統菜單

  trayItem.addMenuDetectListener(new MenuDetectListener() {

  public void menuDetected(MenuDetectEvent e) {

  trayMenu.setVisible(true);

  }

  });

  //注冊窗口監聽

  shell.addShellListener(new ShellAdapter() {

  //點擊窗口最小化按鈕時,窗口隱藏,托盤中顯示圖標

  public void shellIconified(ShellEvent e) {

  toggleDisplay(shell, tray);

  }更多精彩教程请关注:win7系统下载

posted @ 2013-08-09 14:34  豆豆逗逗  阅读(362)  评论(0编辑  收藏  举报