java SWT界面的托盘显示
2013年09月24日
⁄ 综合
⁄ 共 3788字 ⁄ 字号
小 中 大
- //点击关闭或者最小化时程序不会退出而是显示到托盘中 当然也可以是显示在任务栏中的
- 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);
- }
- }