SWT实现系统托盘效果
package lpp; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.*; public class TrayBySwt { public static void main(String[] args) { Display display = new Display(); final Shell shell = new Shell(display); shell.setText("系统托盘BySwt"); shell.setLayout(new FillLayout()); Button button = new Button(shell, SWT.PUSH); button.setText("隐藏窗口显示托盘图标"); ImageData imageData = new ImageData( "E:\\workspace\\myeclipse66\\ra\\Tray\\src\\16.gif"); Image image = new Image(display, imageData); // 取得系统托盘 final Tray tray = display.getSystemTray(); if (tray == null) { System.out.println("当前操作系统不支持托盘图标"); } else { final TrayItem item = new TrayItem(tray, SWT.NONE); item.setToolTipText("我是托盘图标"); item.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { System.out.println("show"); } }); item.addListener(SWT.Hide, new Listener() { public void handleEvent(Event event) { System.out.println("hide"); } }); item.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { System.out.println("selection"); } }); final Menu menu = new Menu(shell, SWT.POP_UP); for (int i = 0; i < 8; i++) { MenuItem mi = new MenuItem(menu, SWT.PUSH); mi.setText("Item" + i); mi.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { System.out.println("selection " + event.widget); } }); if (i == 0) menu.setDefaultItem(mi); } item.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { menu.setVisible(true); } }); item.addListener(SWT.DefaultSelection, new Listener() { public void handleEvent(Event event) { shell.setVisible(true); item.setVisible(false); } }); item.setImage(image); button.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { shell.setVisible(false); item.setVisible(true); } }); item.setVisible(false); } shell.setBounds(50, 50, 300, 200); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } image.dispose(); display.dispose(); } }