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里運行