已經好久沒有寫博客了,前段時間忙着公司實習,做java C/S下的工程,現將開發過程中遇到的難題整理下來,請持續關注!!謝謝!!
好了,話不多說,首先和大家介紹eclipse SWT 中實現工程圖標最小化到托盤,並只能右鍵托盤圖標選擇關閉的功能。並且運行工程任務欄有圖標,但托盤沒有,當關閉桌面上的工程時,圖標只在托盤顯示。部分代碼如下:
</pre><pre name="code" class="html"><span style="font-size:14px;">Display display =new Display();</span>
<span style="font-size:14px;">protected Tray tray;
protected TrayItem trayItem;
protected Menu trayMenu;
protected MenuItem showMenuItem,exitMenuItem;</span>
<span style="font-size:14px;"><span style="white-space:pre"> </span>//給應用程序指定一個系統圖標
<span style="white-space:pre"> </span>shell.setImage(display.getSystemImage(SWT.ICON_WORKING));
//構造系統欄控件
tray = display.getSystemTray();
trayItem = new TrayItem(tray, SWT.NONE);
//程序啓動時,窗口是顯示的,所以任務欄欄圖標隱藏
trayItem.setVisible(false);
trayItem.setToolTipText(shell.getText());
trayItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
toggleDisplay(shell, tray);
}
});
trayMenu = new Menu(shell, SWT.POP_UP);
showMenuItem = new MenuItem(trayMenu, SWT.PUSH);
showMenuItem.setText("顯示窗口(&show)");
//顯示窗口,並隱藏任務欄</span><span style="font-size:14px;">圖標
showMenuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
toggleDisplay(shell, tray);
}
});
trayMenu.setDefaultItem(showMenuItem);
new MenuItem(trayMenu, SWT.SEPARATOR);
//托盤中的退出菜單,程序只能通過這個菜單退出
exitMenuItem = new MenuItem(trayMenu, SWT.PUSH);
exitMenuItem.setText("退出程序(&exit)");
exitMenuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
int closeserial=JOptionPane.showConfirmDialog(null, "確定退出?","提示:", JOptionPane.YES_NO_OPTION);
if(closeserial==0){
shell.dispose();
try {
serialread.close();
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
});
//在托盤圖標點擊鼠標右鍵時的事件,彈出菜單
trayItem.addMenuDetectListener(new MenuDetectListener(){
public void menuDetected(MenuDetectEvent e) {
trayMenu.setVisible(true);
}
});
trayItem.setImage(shell.getImage());
shell.addShellListener(new ShellAdapter() {
//點擊窗口最小化按鈕時,窗口隱藏,托盤顯示圖標
public void shellIconified(ShellEvent e) {
toggleDisplay(shell, tray);
}
//點擊窗口關閉按鈕時,並不終止程序,而是隱藏窗口,同時托盤顯示圖標
public void shellClosed(ShellEvent e) {
e.doit = false; //消耗掉原本系統來處理的事件
toggleDisplay(shell, tray);
}
/* public void shellClosed(ShellEvent e) {
MessageBox messagebox = new MessageBox(shell, SWT.ICON_QUESTION
| SWT.YES | SWT.NO);
messagebox.setText("關閉串口設置:");
messagebox.setMessage("您確定要退出嗎?") ;
int message = messagebox.open();
e.doit = message == SWT.YES;
try {
serialread.close();
} catch (SerialPortException e1) {
e1.printStackTrace();
}
}*/
});</span>