SWT開發Java應用程序GUI入門


    第一次做了Java GUI,我選擇用elipse自己的前段開發工具 SWT/JFace。這篇文章是基於eclipse MARS.2.  用SWT編寫的GUI的風格如下:

                                                                       

1、 SWT中的一些概念

1.1 Display & Shell

    Display 和 Shell 類是SWT中重要的組件。 org.eclipse.swt.widgets.Shell 這個類代表窗口。org.eclipse.swt.widgets.Display主要負責時間循環、字體、顏色、UI線程和其他線程之間的通信(這個功能非常重要,在後面的例子中會說到,UI 線程和非UI線程之間通信,如果不獲取Display的話,會報”無法訪問線程“的錯誤)。Display 是左右SWT組件的基礎。

    每個SWT應用要求至少有一個Display 和一個或多個shell對象。主窗口shell的構造函數把Display作爲默認參數。例如:

Display display = new Display();
Shell shell = new Shell(display);
shell.open();
 
// run the event loop as long as the window is open
while (!shell.isDisposed()) {
   // read the next OS event queue and transfer it to a SWT event
 if (!display.readAndDispatch())
  {
 // if there are currently no other OS event to process
 // sleep until the next OS event is available
   display.sleep();
  }
}
 
// disposes all associated windows and their components
display.dispose();

1.2 SWT 窗口中的部件

    SWT編寫程序的窗口部件都在包org.eclipse.swt.widgets 和 org.eclipse.swt.custom中, 下圖是是一些部件的圖樣:

2  在eclipse中編寫一個簡單的SWT的例子

2.1 創建一個RCP Plugin Progect

    在eclipse中選擇File/New/Other...

不需要創建Workbenck應用,所以選擇下圖的 1 所示的選項
在下圖 2 的地方選擇”yes“,否則創建一個web應用

創建一個工程:

添加依賴的庫文件

2.2 編寫例子

這是一個簡單的例子,沒用用WindowBuilder工具(可以用拖拽的方式製作界面的佈局)

HelloSWT.java

package org.o7planning.tutorial.swt.helloswt;
 
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
 
public class HelloSWT {
 
   public static void main(String[] args) {
       // Create Display
       Display display = new Display();
       // Create Shell (Window) from diplay
       Shell shell = new Shell(display);
 
       shell.open();
 
       while (!shell.isDisposed()) {
           if (!display.readAndDispatch())
               display.sleep();
       }
       display.dispose();
   }
}

右鍵點擊HelloSWT類,選擇Run As/Java Application.


結果如下: 一個空的窗口

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章