一個java swt傳統型程式開發到打包的總結(1)
--概述與關於swt的問題
一、概述:
幾天一直在用金山打字通練習英語(本人英語比較爛),把金山打字能裡面的文章全部掠了N遍。打的沒意思了,想想怎麼能添加一些外部檔案,發現金山打字通內建的外部檔案匯入,太坑了,得往裡面手工複製內容。看了下面的圖就知道效率不高吧。
我就想自己寫一個能夠大量匯入的小軟體,雖然小,可是五髒俱全。(其實主要目的就是想熟悉下java se的開發)
這裡主要寫一下,這次寫程式遇到的問題,的解決方案與注意。以備下次使用! 還是先看下,我的成果吧!
二、關於swt的問題
1,去掉swt視窗的外邊框: shell = new Shell(SWT.NO_TRIM);
2,在去掉swt的視窗邊框以後,swt視窗是不能拖動的,所以要自己添加事件,能夠像正常視窗那樣,按住滑鼠能手動視窗,放開滑鼠視窗移動到滑鼠放開的位置。
1),寫一個內部內,繼承Listener
1 //視窗移動 2 private class ShellMoveListenter implements Listener{ 3 public void handleEvent(Event arg0) { 4 switch (arg0.type) { 5 case SWT.MouseDown: 6 p.x = arg0.x; 7 p.y = arg0.y; 8 break; 9 case SWT.MouseMove: 10 if (p.x == -1) { 11 break; 12 } 13 Point point = shell.toDisplay(arg0.x, arg0.y); 14 shell.setLocation(point.x - p.x, point.y - p.y); 15 break; 16 case SWT.MouseUp: 17 p.x = -1; 18 p.y = -1; 19 break; 20 21 default: 22 break; 23 } 24 }25 }
2),讓shell綁定該件事
1 Listener listener = new ShellMoveListenter();2 shell.addListener(SWT.MouseDown, listener);3 shell.addListener(SWT.MouseMove, listener);4 shell.addListener(SWT.MouseUp, listener);
3,設定視窗顯示在螢幕中間
//得到螢幕解析度 Rectangle area = Display.getDefault().getClientArea(); int windowWidth=area.width; int windowHeight=area.height; //得到視窗寬高 int width=shell.getBounds().width; int height=shell.getBounds().height; //設定視窗位置 int x=(windowWidth-width)/2; int y=(windowHeight-height)/2; shell.setLocation(x, y);
4,開啟檔案夾選項框,並把得到的路徑設定到text中
1 //開啟檔案選項框2 public String openFile(String text){3 DirectoryDialog dd=new DirectoryDialog(shell);4 dd.setText(text);5 dd.setFilterPath("SystemDrive");6 dd.setMessage("這個是什嗎??");7 String selecteddir=dd.open();8 return selecteddir;9 }
button.addSelectionListener(new SelectionAdapter() {public void widgetSelected(SelectionEvent arg0) {String path=openFile("請選擇要匯入的檔案夾目錄!");if(path!=null)fileText.setText(path);}});
5,外部資源路徑問題,比如說背景圖片:建議放在項目下面,這樣打包時可以不用打包資源檔。我的項目結構如下:
1), 不能用:Stringpath=ClassLoader.getSystemResource("res/").getPath()+"bg.jpg";//這個在打包後,會報null 指標異常,具體是怎麼回事,我不知道。
建議用:path1 = System.getProperty("user.dir"); //得到是項目的根目錄。
2),中文中問題:path1=URLDecoder.decode(path1,"UTF-8");//進行轉碼處理。不然會 報找不到路徑異常
6,設定視窗開啟與關閉的漸顯與漸隱效果
1),開啟時:漸顯
int alpha=0; shell.setAlpha(0); shell.open();while(shell.getAlpha()<255){shell.setAlpha(alpha++);try {Thread.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}}
2),關閉時:漸隱
closeBtn.addSelectionListener(new SelectionAdapter(){//關閉視窗public void widgetSelected(SelectionEvent event) {int alpha=254;while(!(shell.getAlpha()<=0)){shell.setAlpha(alpha--);try {Thread.sleep(3);} catch (InterruptedException e2) {e2.printStackTrace();}}shell.close(); }});