SWT学习笔记4——系统托盘 system tray

SWT学习笔记4——系统托盘 system tray

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;

/**
 * 测试SWT的系统托盘用法,同时用到了menu等
 *version: 2012_03_30
 */
public class TestSystemTray {

	public static void main(String[] args) {
		Display display = Display.getDefault();
		final Shell shell = new Shell();
		shell.setSize(230, 150);
		shell.setText("测试系统托盘");
		//添加系统托盘的menu,注意父组件是shell
		final Menu menu = new Menu(shell);
//		shell.setMenu(menu);//加上此句的话在主界面右键也会打开该menu
		
		MenuItem mntmShowShell = new MenuItem(menu, SWT.NONE);
		mntmShowShell.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				System.out.println(e);
				shell.setVisible(true);
				shell.setFocus();//没有此句可能在其他窗口下面
			}
		});
		mntmShowShell.setText("showShell");
		
		MenuItem mntmhideShell = new MenuItem(menu, SWT.NONE);
		mntmhideShell.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				System.out.println(e);
				shell.setVisible(false);
			}
		});
		mntmhideShell.setText("hideShell");

		//
		Tray sysTray=display.getSystemTray();
		TrayItem trayItem = new TrayItem(sysTray, SWT.NONE);
//		trayItem.setImage(display.getSystemImage(SWT.ICON_ERROR));
		trayItem.setImage(new Image(display, "hu.jpg"));
		trayItem.setToolTipText("test system tray");
		//鼠标右键单击系统托盘事件
		trayItem.addMenuDetectListener(new MenuDetectListener() {
			public void menuDetected(MenuDetectEvent e) {
				System.out.println(e);
				menu.setVisible(true);
			}
		});
		//鼠标左键双击系统托盘事件
		trayItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				System.out.println(e);
				shell.setVisible(!shell.isVisible());
				if(shell.isVisible())shell.setFocus();//没有此句可能在其他窗口下面
			}
		});
		
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		
		menu.dispose();
		sysTray.dispose();//没有此句的话任务栏图标不会立即消失,鼠标滑过时才会消失!!!
	}
}

你可能感兴趣的:(System)