最近在用SWT 開發一個Java桌面程序,不同以往用AWT/SWING寫的程序。AWT/SWING寫的程序個人覺得界面很難看,總是不喜歡,而且運行速度也不行。所以看到用SWT程序運行的界面時,給了我一個驚喜。真是看不到以前AWT/SWING寫的界面的影子了,真看不出來是Java程序。SWT程序是調用的系統的小窗口部件,并不是像AWT/SWING自己構造部件,所以SWT程序界面是和操作系統保持一致的。雖然SWT程序還不能像AWT/SWING程序一樣運行在任何平臺,但是現階段SWT程序已經可以不用修改運行在windows, linux等幾個主要的平臺上面了,基本實現了其跨平臺性。由於以上幾個特性,使我對Java GUI編程又有了新的熱情。
SWT寫界面非常簡單,所有的組件都有個統一的構造方法,new Composite(Composite, Style),它去掉了AWT/SWING中用add()方法在面板中添加組件的方式,換成了在定義組件時,用第一個參數說明該組件是屬於那個面板的,另外還有一個可以選擇的組件的樣式,通過不同的樣式,形成組件不同的形態。
下面是一個最簡單的SWT窗口程序
- package com.chengsi.main;
- import org.eclipse.swt.widgets.Display;
- import org.eclipse.swt.widgets.Shell;
- public class Test3 {
- public static void main(String[] args) {
- Display display = Display.getDefault();//相當于顯示器,用來顯示窗口的組件
- Shell shell = new Shell(); //主窗口組件
- shell.setSize(500, 375);
- shell.setText("SWT Application");
- shell.open();
- shell.layout();
- //開始消息循環,直到用戶關閉窗口
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
- }
package com.chengsi.main;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Test3 {
public static void main(String[] args) {
Display display = Display.getDefault();//相當于顯示器,用來顯示窗口的組件
Shell shell = new Shell(); //主窗口組件
shell.setSize(500, 375);
shell.setText("SWT Application");
shell.open();
shell.layout();
//開始消息循環,直到用戶關閉窗口
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
另外,SWT的事件處理與AWT/SWING的事件處理機制是一樣的,可以和AWT/SWING一樣的寫代碼,非常方便。比如在上面程序中加入一個按鈕響應事件,用來顯示一個對話框。
- package com.chengsi.main;
- import org.eclipse.jface.dialogs.MessageDialog;
- import org.eclipse.swt.SWT;
- import org.eclipse.swt.events.SelectionAdapter;
- import org.eclipse.swt.events.SelectionEvent;
- import org.eclipse.swt.layout.RowLayout;
- import org.eclipse.swt.widgets.Button;
- import org.eclipse.swt.widgets.Display;
- import org.eclipse.swt.widgets.Shell;
- public class Test3 {
- public static void main(String[] args) {
- Display display = Display.getDefault(); //相當于顯示器,用來顯示窗口的組件
- final Shell shell = new Shell();//主窗口組件 ,要在匿名內部類中使用,所以用final修飾
- shell.setSize(500, 375);
- shell.setText("SWT Application");
- shell.setLayout(new RowLayout());//設置布局,相當于AWT/SWING中的FlowLayout
- shell.open();
- shell.layout();
- Button btn = new Button(shell, SWT.PUSH);//在shell面板中加入一個普通按鈕
- btn.setText("單擊我");
- //加入選擇事件監聽
- btn.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- //彈出一個對話框
- MessageDialog.openInformation(shell, "對話框", "按鈕單擊事件"); }
- });
- btn.pack();//以適當的大小顯示
- //開始消息循環,直到用戶關閉窗口
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
- }