用SWT在系统托盘区创建一个托盘的方法

在我的这篇随笔http://www.blogjava.net/lzqdiy/archive/2007/05/13/117086.html中,我使用了JDK1.6中的AWT来创建一个系统托盘,博友们强烈建议我用SWT来实现,我也感觉原来的程序中既有AWT又有SWT,有点不伦不类,于是我将程序中系统托盘的实现部分改成了用SWT实现,源程序如下:

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
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.Text;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

import com.swtdesigner.SWTResourceManager;

public class QQ
{

    
private Text introText;

    
private Combo constellationCombo;

    
private Combo jobCombo;

    
private Combo animalCombo;

    
private Combo bloodCombo;

    
private Text schoolText;

    
private Text frontPageText;

    
private Text oleText;

    
private Text nameText;

    
private Combo sexCombo;

    
private Canvas rank;

    
private Text attachName;

    
private Text nickName;

    
private Text text;

    
private List selectList;

    
private StackLayout stackLayout = new StackLayout();

    
private Composite composite;

    
private Composite composite_1;

    
private Composite rightComp;

    
private static Image image;

    
private static Image rankimage;

    
// private static SystemTray st;

    
/**
     * Launch the application
     * 
     * 
@param args
     
*/

    
public static void main(String[] args)
    
{
        
try
        
{
            QQ window 
= new QQ();
            window.open();
        }
 catch (Exception e)
        
{
            e.printStackTrace();
        }

    }


    
public static void createPopupMenu()
    
{

    }


    
/**
     * Open the window
     
*/

    
public void open()
    
{
        
final Display display = Display.getDefault();
        
final Shell shell = new Shell();

        Image image2 
= new Image(display, "qq.gif");
        
final Tray tray = display.getSystemTray();
        
final TrayItem trayItem = new TrayItem(tray, SWT.NONE);
        trayItem.setToolTipText(
"QQ 176870965");
        trayItem.setImage(image2);

        
//添加右键菜单
        final Menu menu = new Menu(shell, SWT.POP_UP);
        MenuItem menuItemMaximize 
= new MenuItem(menu, SWT.PUSH);// 最大化菜单
        menuItemMaximize.setText("最大化");
        menuItemMaximize.addSelectionListener(
new SelectionListener()
        
{
            
public void widgetSelected(SelectionEvent e)
            
{
                shell.setVisible(
true);
                shell.setMaximized(
true);
            }


            
public void widgetDefaultSelected(SelectionEvent e)
            
{
                
// widgetSelected(e);
            }

        }
);

        MenuItem menuItemMinimize 
= new MenuItem(menu, SWT.PUSH);// 最小化菜单
        menuItemMinimize.setText("最小化");
        menuItemMinimize.addSelectionListener(
new SelectionListener()
        
{
            
public void widgetSelected(SelectionEvent e)
            
{
                shell.setMinimized(
true);
            }


            
public void widgetDefaultSelected(SelectionEvent e)
            
{
                
// widgetSelected(e);
            }

        }
);

        
new MenuItem(menu, SWT.SEPARATOR);// 分割条

        MenuItem menuItemClose 
= new MenuItem(menu, SWT.PUSH);// 关闭菜单
        menuItemClose.setText("退出");
        menuItemClose.addSelectionListener(
new SelectionListener()
        
{
            
public void widgetDefaultSelected(SelectionEvent e)
            
{
                Display.getCurrent().close();
            }


            
public void widgetSelected(SelectionEvent e)
            
{
                widgetDefaultSelected(e);
            }

        }
);
        
//右键单击弹出菜单
        trayItem.addListener(SWT.MenuDetect, new Listener()
        
{
            
public void handleEvent(Event event)
            
{
                System.out.println(
"右键菜单");
                menu.setLocation(display.getCursorLocation());
                menu.setVisible(
true);
            }

        }
);

        trayItem.addSelectionListener(
new SelectionListener()
        
{
            
// 左键单击
            public void widgetSelected(SelectionEvent e)
            
{
                System.out.println(
"左键单击");
                
// 左键单击时 ,隐藏,显示主窗口
                if (shell.isVisible())
                
{
                    shell.setVisible(
false);
                }
 else
                
{
                    shell.setVisible(
true);
                    shell.forceActive();
                }

            }


            
// 左键双击,右键双击,都是它
            public void widgetDefaultSelected(SelectionEvent e)
            
{
                System.out.println(
"双击");
            }

        }
);

        

        shell.setBackground(SWTResourceManager.getColor(
103172231));
        shell.setLayout(
new GridLayout());
        shell.setSize(
500400);
        shell.setLocation(
262184);
        shell.setText(
"QQ2006设置");
        
//

        shell.open();

        
final SashForm sashForm = new SashForm(shell, SWT.NONE);
        sashForm.setForeground(SWTResourceManager.getColor(
103172231));
        sashForm.setLayoutData(
new GridData(GridData.FILL_BOTH));
        selectList 
= new List(sashForm, SWT.NONE);
        selectList.addMouseListener(
new MouseAdapter()
        
{
            
public void mouseDown(MouseEvent arg0)
            
{
                
int selectionIndex = selectList.getSelectionIndex();
                
if (selectionIndex == 0)
                    stackLayout.topControl 
= composite;
                
else
                    stackLayout.topControl 
= composite_1;
                rightComp.layout();
            }

        }
);
        selectList.setItems(
new String[]
        
"个人资料""联系方式" });

        rightComp 
= new Composite(sashForm, SWT.NONE);
        rightComp.setBackground(SWTResourceManager.getColor(
23255255));

        rightComp.setLayout(stackLayout);

        composite 
= new Composite(rightComp, SWT.BORDER);
        composite.setForeground(SWTResourceManager.getColor(
00255));
        composite.setBackground(SWTResourceManager.getColor(
255255255));
        GridLayout gridLayout 
= new GridLayout(6false);
        gridLayout.horizontalSpacing 
= 10;
        composite.setLayout(gridLayout);
        
final Label titleLabel = new Label(composite, SWT.NONE);
        titleLabel.setForeground(SWTResourceManager.getColor(
12597));
        titleLabel.setBackground(SWTResourceManager.getColor(
229241253));
        titleLabel.setFont(SWTResourceManager.getFont(
""11, SWT.BOLD));
        titleLabel.setText(
"个人设置-个人资料");
        GridData gridData3 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData3.horizontalSpan 
= 6;
        titleLabel.setLayoutData(gridData3);
        
final Label label1 = new Label(composite, SWT.NONE);
        label1.setBackground(SWTResourceManager.getColor(
255255255));
        label1.setText(
"用户号码:");
        text 
= new Text(composite, SWT.READ_ONLY | SWT.BORDER);
        text.setBackground(SWTResourceManager.getColor(
255255255));
        GridData gridData 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan 
= 3;
        text.setLayoutData(gridData);
        
final Composite photoComp = new Composite(composite, SWT.NONE);
        photoComp.setBackground(SWTResourceManager.getColor(
255255255));
        gridData 
= new GridData(GridData.HORIZONTAL_ALIGN_FILL
                
| GridData.VERTICAL_ALIGN_FILL);
        gridData.horizontalSpan 
= 2;
        gridData.verticalSpan 
= 2;
        photoComp.setLayoutData(gridData);
        photoComp.setLayout(
new GridLayout(2false));

        
final Composite tempComp = new Composite(photoComp, SWT.BORDER);
        tempComp.setLayout(
new FillLayout());
        tempComp.setLayoutData(
new GridData(3030));

        
final Canvas canvas = new Canvas(tempComp, SWT.NONE);
        image 
= new Image(display, "mum.jpg");
        canvas.redraw();
        canvas.addPaintListener(
new PaintListener()
        
{
            
public void paintControl(PaintEvent event)
            
{
                event.gc.drawImage(image, 
00);
            }

        }
);

        
final Button setPhotoButton = new Button(photoComp, SWT.DOWN);
        setPhotoButton.setLayoutData(
new GridData(GridData.VERTICAL_ALIGN_END));
        setPhotoButton.setText(
"更改");

        
final Label label2 = new Label(composite, SWT.NONE);
        label2.setBackground(SWTResourceManager.getColor(
255255255));
        label2.setText(
"用户昵称:");

        nickName 
= new Text(composite, SWT.BORDER);
        gridData 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan 
= 3;
        nickName.setLayoutData(gridData);

        
final Label label3 = new Label(composite, SWT.NONE);
        label3.setBackground(SWTResourceManager.getColor(
255255255));
        gridData 
= new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
        label3.setLayoutData(gridData);
        label3.setText(
"个性签名:");

        attachName 
= new Text(composite, SWT.BORDER);
        gridData 
= new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan 
= 5;
        gridData.verticalSpan 
= 2;
        attachName.setLayoutData(gridData);
        
final Label label22 = new Label(composite, SWT.NONE);
        
final Label labe24 = new Label(composite, SWT.NONE);
        labe24.setBackground(SWTResourceManager.getColor(
255255255));
        labe24.setText(
"会员阶段:");
        
final Label labe23 = new Label(composite, SWT.NONE);
        
final Label label4 = new Label(composite, SWT.NONE);
        label4.setBackground(SWTResourceManager.getColor(
255255255));
        label4.setText(
"QQ等级:");

        rank 
= new Canvas(composite, SWT.NONE);
        rank.addPaintListener(
new PaintListener()
        
{
            
public void paintControl(PaintEvent event)
            
{
                event.gc.drawImage(rankimage, 
00);
            }

        }
);
        rank.setBackground(SWTResourceManager.getColor(
255255255));
        gridData 
= new GridData(SWT.FILL, SWT.CENTER, truefalse31);
        gridData.heightHint 
= 17;
        rank.setLayoutData(gridData);
        rankimage 
= new Image(display, "rank.jpg");
        rank.redraw();

        
final Label label5 = new Label(composite, SWT.NONE);
        label5.setBackground(SWTResourceManager.getColor(
255255255));
        label5.setLayoutData(
new GridData());
        label5.setText(
"性    别:");

        sexCombo 
= new Combo(composite, SWT.NONE);
        sexCombo.setBackground(SWTResourceManager.getColor(
255255255));
        sexCombo.setForeground(SWTResourceManager.getColor(
000));
        sexCombo.setItems(
new String[]
        
"""" });
        sexCombo.setText(
"");

        
final Label label6 = new Label(composite, SWT.NONE);
        label6.setBackground(SWTResourceManager.getColor(
255255255));
        label6.setText(
"姓名:");

        nameText 
= new Text(composite, SWT.BORDER);
        nameText.setLayoutData(
new GridData(GridData.HORIZONTAL_ALIGN_FILL));

        
final Label label7 = new Label(composite, SWT.NONE);
        label7.setBackground(SWTResourceManager.getColor(
255255255));
        label7.setText(
"年龄:");

        oleText 
= new Text(composite, SWT.BORDER);
        oleText.setLayoutData(
new GridData(GridData.HORIZONTAL_ALIGN_FILL));

        
final Label label8 = new Label(composite, SWT.NONE);
        label8.setBackground(SWTResourceManager.getColor(
255255255));
        label8.setText(
"毕业院校:");

        schoolText 
= new Text(composite, SWT.BORDER);
        gridData 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan 
= 3;
        schoolText.setLayoutData(gridData);

        
final Label label9 = new Label(composite, SWT.NONE);
        label9.setBackground(SWTResourceManager.getColor(
255255255));
        label9.setText(
"生肖:");

        animalCombo 
= new Combo(composite, SWT.NONE);
        animalCombo.setBackground(SWTResourceManager.getColor(
255255255));
        animalCombo.setItems(
new String[]
        
"""""" });
        animalCombo.setText(
"");
        animalCombo.setLayoutData(
new GridData(GridData.HORIZONTAL_ALIGN_FILL));

        
final Label label10 = new Label(composite, SWT.NONE);
        label10.setBackground(SWTResourceManager.getColor(
255255255));
        label10.setText(
"职    业:");

        jobCombo 
= new Combo(composite, SWT.BORDER);
        jobCombo.setBackground(SWTResourceManager.getColor(
255255255));
        jobCombo.setItems(
new String[]
        
"计算机业""学生" });
        jobCombo.setText(
"计算机业");
        gridData 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan 
= 3;
        jobCombo.setLayoutData(gridData);

        
final Label label11 = new Label(composite, SWT.NONE);
        label11.setBackground(SWTResourceManager.getColor(
255255255));
        label11.setText(
"星座:");

        constellationCombo 
= new Combo(composite, SWT.NONE);
        constellationCombo.setBackground(SWTResourceManager.getColor(
255255,
                
255));
        constellationCombo.setItems(
new String[]
        
"牧羊座""金牛座" });
        constellationCombo.setText(
"牧羊座");
        constellationCombo.setLayoutData(
new GridData(
                GridData.HORIZONTAL_ALIGN_FILL));

        
final Label label28 = new Label(composite, SWT.NONE);
        label28.setBackground(SWTResourceManager.getColor(
255255255));
        label28.setText(
"个人主页:");

        frontPageText 
= new Text(composite, SWT.BORDER);
        gridData 
= new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan 
= 3;
        frontPageText.setLayoutData(gridData);

        
final Label label29 = new Label(composite, SWT.NONE);
        label29.setBackground(SWTResourceManager.getColor(
255255255));
        label29.setText(
"血型:");

        bloodCombo 
= new Combo(composite, SWT.NONE);
        bloodCombo.setBackground(SWTResourceManager.getColor(
255255255));
        bloodCombo.setItems(
new String[]
        
"A型""B型""O型""AB型""其他" });
        bloodCombo.setText(
"O型");
        bloodCombo.setLayoutData(
new GridData(GridData.HORIZONTAL_ALIGN_FILL));

        
final Label introLabel = new Label(composite, SWT.NONE);
        introLabel.setBackground(SWTResourceManager.getColor(
255255255));
        introLabel
                .setLayoutData(
new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
        introLabel.setText(
"个人说明:");

        introText 
= new Text(composite, SWT.WRAP | SWT.BORDER);
        gridData 
= new GridData(GridData.HORIZONTAL_ALIGN_FILL
                
| GridData.FILL_VERTICAL);
        gridData.horizontalSpan 
= 5;
        introText.setLayoutData(gridData);

        composite_1 
= new Composite(rightComp, SWT.NONE);
        composite_1.setLayout(
new FillLayout());

        
final Label label = new Label(composite_1, SWT.NONE);
        label.setText(
"联系方式面板");
        stackLayout.topControl 
= composite;

        
final Composite buttonComp = new Composite(shell, SWT.NONE);
        buttonComp.setBackground(SWTResourceManager.getColor(
107172231));
        gridData 
= new GridData();
        gridData.horizontalAlignment 
= GridData.END;
        buttonComp.setLayoutData(gridData);
        RowLayout rowLayout 
= new RowLayout();
        rowLayout.spacing 
= 15;
        buttonComp.setLayout(rowLayout);

        
final Button button = new Button(buttonComp, SWT.NONE);
        button.setForeground(SWTResourceManager.getColor(
0255255));
        button.setBackground(SWTResourceManager.getColor(
182222255));
        button.setText(
"   确定   ");

        
final Button button_1 = new Button(buttonComp, SWT.NONE);
        button_1.setText(
"   取消   ");

        
final Button button_2 = new Button(buttonComp, SWT.NONE);
        button_2.setText(
"   应用   ");
        sashForm.setWeights(
new int[]
        
14 });
        shell.layout();
        
while (!shell.isDisposed())
        
{
            
if (!display.readAndDispatch())
                display.sleep();
        }

    }

}

package com.swtdesigner;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;

/**
 * Utility class for managing OS resources associated with SWT controls such as
 * colors, fonts, images, etc.
 * 
 * !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code>
 * method to release the operating system resources managed by cached objects
 * when those objects and OS resources are no longer needed (e.g. on
 * application shutdown)
 * 
 * This class may be freely distributed as part of any application or plugin.
 * <p>
 * Copyright (c) 2003 - 2005, Instantiations, Inc. <br>All Rights Reserved
 * 
 * 
@author scheglov_ke
 * 
@author Dan Rubel
 
*/

public class SWTResourceManager {

    
/**
     * Dispose of cached objects and their underlying OS resources. This should
     * only be called when the cached objects are no longer needed (e.g. on
     * application shutdown)
     
*/

    
public static void dispose() {
        disposeColors();
        disposeFonts();
        disposeImages();
        disposeCursors();
    }


    
//////////////////////////////
    
// Color support
    //////////////////////////////

    
/**
     * Maps RGB values to colors
     
*/

    
private static HashMap<RGB, Color> m_ColorMap = new HashMap<RGB, Color>();

    
/**
     * Returns the system color matching the specific ID
     * 
@param systemColorID int The ID value for the color
     * 
@return Color The system color matching the specific ID
     
*/

    
public static Color getColor(int systemColorID) {
        Display display 
= Display.getCurrent();
        
return display.getSystemColor(systemColorID);
    }


    
/**
     * Returns a color given its red, green and blue component values
     * 
@param r int The red component of the color
     * 
@param g int The green component of the color
     * 
@param b int The blue component of the color
     * 
@return Color The color matching the given red, green and blue componet values
     
*/

    
public static Color getColor(int r, int g, int b) {
        
return getColor(new RGB(r, g, b));
    }


    
/**
     * Returns a color given its RGB value
     * 
@param rgb RGB The RGB value of the color
     * 
@return Color The color matching the RGB value
     
*/

    
public static Color getColor(RGB rgb) {
        Color color 
= m_ColorMap.get(rgb);
        
if (color == null{
            Display display 
= Display.getCurrent();
            color 
= new Color(display, rgb);
            m_ColorMap.put(rgb, color);
        }

        
return color;
    }


    
/**
     * Dispose of all the cached colors
     
*/

    
public static void disposeColors() {
        
for (Iterator iter = m_ColorMap.values().iterator(); iter.hasNext();)
             ((Color) iter.next()).dispose();
        m_ColorMap.clear();
    }


    
//////////////////////////////
    
// Image support
    //////////////////////////////

    
/**
     * Maps image names to images
     
*/

    
private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>();

    
/**
     * Maps images to image decorators
     
*/

    
private static HashMap<Image, HashMap<Image, Image>> m_ImageToDecoratorMap = new HashMap<Image, HashMap<Image, Image>>();

    
/**
     * Returns an image encoded by the specified input stream
     * 
@param is InputStream The input stream encoding the image data
     * 
@return Image The image encoded by the specified input stream
     
*/

    
protected static Image getImage(InputStream is) {
        Display display 
= Display.getCurrent();
        ImageData data 
= new ImageData(is);
        
if (data.transparentPixel > 0)
            
return new Image(display, data, data.getTransparencyMask());
        
return new Image(display, data);
    }


    
/**
     * Returns an image stored in the file at the specified path
     * 
@param path String The path to the image file
     * 
@return Image The image stored in the file at the specified path
     
*/

    
public static Image getImage(String path) {
        
return getImage("default", path); //$NON-NLS-1$
    }


    
/**
     * Returns an image stored in the file at the specified path
     * 
@param section The section to which belongs specified image
     * 
@param path String The path to the image file
     * 
@return Image The image stored in the file at the specified path
     
*/

    
public static Image getImage(String section, String path) {
        String key 
= section + '|' + SWTResourceManager.class.getName() + '|' + path;
        Image image 
= m_ClassImageMap.get(key);
        
if (image == null{
            
try {
                FileInputStream fis 
= new FileInputStream(path);
                image 
= getImage(fis);
                m_ClassImageMap.put(key, image);
                fis.close();
            }
 catch (Exception e) {
                image 
= getMissingImage();
                m_ClassImageMap.put(key, image);
            }

        }

        
return image;
    }


    
/**
     * Returns an image stored in the file at the specified path relative to the specified class
     * 
@param clazz Class The class relative to which to find the image
     * 
@param path String The path to the image file
     * 
@return Image The image stored in the file at the specified path
     
*/

    
public static Image getImage(Class clazz, String path) {
        String key 
= clazz.getName() + '|' + path;
        Image image 
= m_ClassImageMap.get(key);
        
if (image == null{
            
try {
                
if (path.length() > 0 && path.charAt(0== '/'{
                    String newPath 
= path.substring(1, path.length());
                    image 
= getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath)));
                }
 else {
                    image 
= getImage(clazz.getResourceAsStream(path));
                }

                m_ClassImageMap.put(key, image);
            }
 catch (Exception e) {
                image 
= getMissingImage();
                m_ClassImageMap.put(key, image);
            }

        }

        
return image;
    }


    
private static final int MISSING_IMAGE_SIZE = 10;
    
private static Image getMissingImage() {
        Image image 
= new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
        
//
        GC gc = new GC(image);
        gc.setBackground(getColor(SWT.COLOR_RED));
        gc.fillRectangle(
00, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
        gc.dispose();
        
//
        return image;
    }


    
/**
     * Style constant for placing decorator image in top left corner of base image.
     
*/

    
public static final int TOP_LEFT = 1;
    
/**
     * Style constant for placing decorator image in top right corner of base image.
     
*/

    
public static final int TOP_RIGHT = 2;
    
/**
     * Style constant for placing decorator image in bottom left corner of base image.
     
*/

    
public static final int BOTTOM_LEFT = 3;
    
/**
     * Style constant for placing decorator image in bottom right corner of base image.
     
*/

    
public static final int BOTTOM_RIGHT = 4;
    
    
/**
     * Returns an image composed of a base image decorated by another image
     * 
@param baseImage Image The base image that should be decorated
     * 
@param decorator Image The image to decorate the base image
     * 
@return Image The resulting decorated image
     
*/

    
public static Image decorateImage(Image baseImage, Image decorator) {
        
return decorateImage(baseImage, decorator, BOTTOM_RIGHT);
    }

    
    
/**
     * Returns an image composed of a base image decorated by another image
     * 
@param baseImage Image The base image that should be decorated
     * 
@param decorator Image The image to decorate the base image
     * 
@param corner The corner to place decorator image
     * 
@return Image The resulting decorated image
     
*/

    
public static Image decorateImage(Image baseImage, Image decorator, int corner) {
        HashMap
<Image, Image> decoratedMap = m_ImageToDecoratorMap.get(baseImage);
        
if (decoratedMap == null{
            decoratedMap 
= new HashMap<Image, Image>();
            m_ImageToDecoratorMap.put(baseImage, decoratedMap);
        }

        Image result 
= decoratedMap.get(decorator);
        
if (result == null{
            Rectangle bid 
= baseImage.getBounds();
            Rectangle did 
= decorator.getBounds();
            result 
= new Image(Display.getCurrent(), bid.width, bid.height);
            GC gc 
= new GC(result);
            gc.drawImage(baseImage, 
00);
            
//
            if (corner == TOP_LEFT) {
                gc.drawImage(decorator, 
00);
            }
 else if (corner == TOP_RIGHT) {
                gc.drawImage(decorator, bid.width 
- did.width - 10);
            }
 else if (corner == BOTTOM_LEFT) {
                gc.drawImage(decorator, 
0, bid.height - did.height - 1);
            }
 else if (corner == BOTTOM_RIGHT) {
                gc.drawImage(decorator, bid.width 
- did.width - 1, bid.height - did.height - 1);
            }

            
//
            gc.dispose();
            decoratedMap.put(decorator, result);
        }

        
return result;
    }


    
/**
     * Dispose all of the cached images
     
*/

    
public static void disposeImages() {
        
for (Iterator I = m_ClassImageMap.values().iterator(); I.hasNext();)
             ((Image) I.next()).dispose();
        m_ClassImageMap.clear();
        
//
        for (Iterator I = m_ImageToDecoratorMap.values().iterator(); I.hasNext();) {
            HashMap decoratedMap 
= (HashMap) I.next();
            
for (Iterator J = decoratedMap.values().iterator(); J.hasNext();) {
                Image image 
= (Image) J.next();
                image.dispose();
            }

        }

    }


    
/**
     * Dispose cached images in specified section
     * 
@param section the section do dispose
     
*/

    
public static void disposeImages(String section) {
        
for (Iterator I = m_ClassImageMap.keySet().iterator(); I.hasNext();) {
            String key 
= (String) I.next();
            
if (!key.startsWith(section + '|'))
                
continue;
            Image image 
= m_ClassImageMap.get(key);
            image.dispose();
            I.remove();
        }

    }


    
//////////////////////////////
    
// Font support
    //////////////////////////////

    
/**
     * Maps font names to fonts
     
*/

    
private static HashMap<String, Font> m_FontMap = new HashMap<String, Font>();

    
/**
     * Maps fonts to their bold versions
     
*/

    
private static HashMap<Font, Font> m_FontToBoldFontMap = new HashMap<Font, Font>();

    
/**
     * Returns a font based on its name, height and style
     * 
@param name String The name of the font
     * 
@param height int The height of the font
     * 
@param style int The style of the font
     * 
@return Font The font matching the name, height and style
     
*/

    
public static Font getFont(String name, int height, int style) {
        
return getFont(name, height, style, falsefalse);
    }



    
/**
     * Returns a font based on its name, height and style. 
     * Windows-specific strikeout and underline flags are also supported.
     * 
@param name String The name of the font
     * 
@param size int The size of the font
     * 
@param style int The style of the font
     * 
@param strikeout boolean The strikeout flag (warning: Windows only)
     * 
@param underline boolean The underline flag (warning: Windows only)
     * 
@return Font The font matching the name, height, style, strikeout and underline
     
*/

    
public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) {
        String fontName 
= name + '|' + size + '|' + style + '|' + strikeout + '|' + underline;
        Font font 
= m_FontMap.get(fontName);
        
if (font == null{
            FontData fontData 
= new FontData(name, size, style);
            
if (strikeout || underline) {
                
try {
                    Class logFontClass 
= Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$
                    Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$
                    if (logFont != null && logFontClass != null{
                        
if (strikeout) {
                            logFontClass.getField(
"lfStrikeOut").set(logFont, new Byte((byte1)); //$NON-NLS-1$
                        }

                        
if (underline) {
                            logFontClass.getField(
"lfUnderline").set(logFont, new Byte((byte1)); //$NON-NLS-1$
                        }

                    }

                }
 catch (Throwable e) {
                    System.err.println(
                        
"Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$
                }

            }

            font 
= new Font(Display.getCurrent(), fontData);
            m_FontMap.put(fontName, font);
        }

        
return font;
    }

    

    
/**
     * Return a bold version of the give font
     * 
@param baseFont Font The font for whoch a bold version is desired
     * 
@return Font The bold version of the give font
     
*/

    
public static Font getBoldFont(Font baseFont) {
        Font font 
= m_FontToBoldFontMap.get(baseFont);
        
if (font == null{
            FontData fontDatas[] 
= baseFont.getFontData();
            FontData data 
= fontDatas[0];
            font 
= new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD);
            m_FontToBoldFontMap.put(baseFont, font);
        }

        
return font;
    }


    
/**
     * Dispose all of the cached fonts
     
*/

    
public static void disposeFonts() {
        
for (Iterator iter = m_FontMap.values().iterator(); iter.hasNext();)
             ((Font) iter.next()).dispose();
        m_FontMap.clear();
    }


    
//////////////////////////////
    
// CoolBar support
    //////////////////////////////

    
/**
     * Fix the layout of the specified CoolBar
     * 
@param bar CoolBar The CoolBar that shgoud be fixed
     
*/

    
public static void fixCoolBarSize(CoolBar bar) {
        CoolItem[] items 
= bar.getItems();
        
// ensure that each item has control (at least empty one)
        for (int i = 0; i < items.length; i++{
            CoolItem item 
= items[i];
            
if (item.getControl() == null)
                item.setControl(
new Canvas(bar, SWT.NONE) {
                @Override
                
public Point computeSize(int wHint, int hHint, boolean changed) {
                    
return new Point(2020);
                }

            }
);
        }

        
// compute size for each item
        for (int i = 0; i < items.length; i++{
            CoolItem item 
= items[i];
            Control control 
= item.getControl();
            control.pack();
            Point size 
= control.getSize();
            item.setSize(item.computeSize(size.x, size.y));
        }

    }


    
//////////////////////////////
    
// Cursor support
    //////////////////////////////

    
/**
     * Maps IDs to cursors
     
*/

    
private static HashMap<Integer, Cursor> m_IdToCursorMap = new HashMap<Integer, Cursor>();
 
    
/**
     * Returns the system cursor matching the specific ID
     * 
@param id int The ID value for the cursor
     * 
@return Cursor The system cursor matching the specific ID
     
*/

    
public static Cursor getCursor(int id) {
        Integer key 
= new Integer(id);
        Cursor cursor 
= m_IdToCursorMap.get(key);
        
if (cursor == null{
            cursor 
= new Cursor(Display.getDefault(), id);
            m_IdToCursorMap.put(key, cursor);
        }

        
return cursor;
    }

 
    
/**
     * Dispose all of the cached cursors
     
*/

    
public static void disposeCursors() {
        
for (Iterator iter = m_IdToCursorMap.values().iterator(); iter.hasNext();)
             ((Cursor) iter.next()).dispose();
        m_IdToCursorMap.clear();
    }

}

运行效果:



posted on 2007-05-14 18:05 我为J狂 阅读(2096) 评论(3)  编辑  收藏 所属分类: 图形用户界面

评论

# re: 用SWT在系统托盘区创建一个托盘的方法 2007-05-14 20:20 Pande

你的小企鹅图标背景是白的,弄个背景透明的图标就更好看了  回复  更多评论   

# re: 用SWT在系统托盘区创建一个托盘的方法 2007-05-15 10:57 我为J狂

@Pande
看来我得找一张透明的图片了,呵呵。  回复  更多评论   

# re: 用SWT在系统托盘区创建一个托盘的方法 2007-05-17 10:29 haha~~~~

呵呵 不错  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
<2007年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(11)

随笔分类(48)

文章分类(29)

常去逛逛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜