javaSWT界面的托盘显示

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

  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);}//點擊窗口關閉時,并不終止程序,而是隱藏窗口,同時托盤中顯示圖標public void shellClosed(ShellEvent e) {e.doit = false; //取消關閉操作toggleDisplay(shell, tray);}});shell.setSize(320, 240);center(shell);shell.open();while(!shell.isDisposed()) {if(!display.readAndDispatch()) {display.sleep();}}display.dispose();}/*** 窗口是可見狀態時,則隱藏窗口,在托盤中顯示程序圖標* 窗口是隱藏狀態時,則顯示窗口,將托盤中圖標刪除*/private static void toggleDisplay(Shell shell, Tray tray) {try {shell.setVisible(!shell.isVisible()); //控制窗口顯示tray.getItem(0).setVisible(!shell.isVisible()); //控制托盤圖標顯示//如果窗口是顯示狀態if(shell.getVisible()) {shell.setMinimized(false); //阻止窗口最小化shell.setActive(); //激活窗口}} catch(Exception e) {e.printStackTrace();}}/*** 窗口居中顯示*/private static void center(Shell shell) {Monitor monitor = shell.getMonitor();Rectangle bounds = monitor.getBounds();Rectangle rect = shell.getBounds();int x = bounds.x + (bounds.width – rect.width)/2;int y = bounds.y + (bounds.height – rect.height)/2;shell.setLocation(x, y);}}

最大的成功在于最大的付出。

javaSWT界面的托盘显示

相关文章:

你感兴趣的文章:

标签云: