SWT也支持系统托盘耶!

本人的博客大半年没更新了,主要原因就是一个字——懒!再继续懒下去的话,地里就只能收获干草了。

这几天重新开始学习SWT,发现有一个之前被忽略的widget——Tray,使用VB/VC/Delphi之类开发工具做UI的程序员们对它一定不陌生,就是系统托盘——在任务栏显示一个小图标,鼠标点击图标可以弹出菜单。

SWT居然早就实现了这一功能,再一google,靠!早在公元2005年就有一大筐相关文章了,自己太孤陋寡闻了!

以下是本人在一英文网站发现的例子http://www.eclipsezone.com/eclipse/forums/t44619.html,本人稍作改动,添加一个空白主窗口,用户窗口最小化时,窗口隐藏,鼠标双击tray,主窗口显示。

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

public class SysTrayTest {
	public static void main(String[] args) {
		
		final Display display = Display.getDefault();
		final Shell shell = new Shell(display);
		// Retrieves the system tray singleton
		final Tray tray = display.getSystemTray();
		// Creates a new tray item (displayed as an icon)
		final TrayItem item = new TrayItem(tray, 0);
		final Image image = new Image(display, "sample.gif");
		item.setToolTipText("SWT Tray in action");
		item.setImage(image);
		// The tray item can only receive Selection/DefaultSelection (left click) or
		// MenuDetect (right click) events
		item.addListener(SWT.MenuDetect, new Listener() {
			public void handleEvent(Event event) {
				// We need a Shell as the parent of our menu
				Shell s = new Shell(event.display);
				// Style must be pop up
				Menu m = new Menu(s, SWT.POP_UP);
				// Creates a new menu item that terminates the program
				// when selected
				MenuItem exit = new MenuItem(m, SWT.NONE);
				exit.setText("Goodbye!");
				exit.addListener(SWT.Selection, new Listener() {
					public void handleEvent(Event event) {
						shell.close();
					}
				});
				// We need to make the menu visible
				m.setVisible(true);
			};
		});
		
		item.addListener(SWT.DefaultSelection, new Listener(){
			public void handleEvent(Event event) {
				shell.setVisible(true);
				shell.setMinimized(false);
			}
		});
		
		shell.addShellListener(new ShellAdapter(){
			public void shellIconified(ShellEvent e) {
				shell.setVisible(false);
			}
		});
		
		shell.setSize(160,90);
	    shell.open();
	    while (!shell.isDisposed()) {
	    	if (!display.readAndDispatch())
				display.sleep();
	    }
	    image.dispose();
	    display.dispose();
	    
	}
	}

 

你可能感兴趣的:(eclipse,UP,vb,vc++,Delphi)