swt 簡單的托盤程式

fightplane發表於2007-11-16

swt 簡單的托盤程式
java寫和作業系統相關的程式難度非常大。在java 6出現之前,如果你想實現一個托盤程式,最簡單的就是用swt了。
通過google我找到了一段程式碼。
其實很簡單。主要的程式碼如下:
             final Tray tray = display.getSystemTray();
            final TrayItem trayItem = new TrayItem(tray, SWT.NONE);
            Image image = new Image (display, 16, 16);
            trayItem.setImage(image);
知道了重點,事情變的很簡單了。看看所有程式
//-----------------
public class SystemTray extends Shell {
    public static void main(String args[]) {
        try {
            Display display = Display.getDefault();
            SystemTray shell = new SystemTray(display, SWT.SHELL_TRIM);
           // shell.createSystemTray(shell);
            final Tray tray = display.getSystemTray();
            final TrayItem trayItem = new TrayItem(tray, SWT.NONE);
            Image image = new Image (display, 16, 16);
            trayItem.setImage(image);
            shell.open();
            shell.layout();
            while (!shell.isDisposed()) {
                if (!display.readAndDispatch())
                    display.sleep();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public SystemTray(Display display, int style) {
        super(display, style);
        createContents();
    }

    /**
     * Create contents of the window
     */
    protected void createContents() {
        setText("SWT Application");
        setSize(500, 375);

    }
    //swt 預設情況下不允許shell被繼承
    //所以我過載了父類的方法
    protected void checkSubclass() {
         }
}
//--------------------
如果你想成功執行以上程式碼,你最好在eclipse下新建一個swt的類。具體操作你搜尋一下吧。
但是上面的程式碼只是加入了托盤,這可能是最簡單的實現托盤的程式了。我們加入事件處理,讓程式能夠最大和最小化。然後把托盤用圖片來表示。
詳細的程式碼不參考
下載 到eclipse裡執行 
 

相關文章