Eclipse Rcp系列 http://www.blogjava.net/dreamstone/archive/2007/02/08/98706.html
Eclise Rcp 系列一 第一個SWT程序
寫在開始:
由于工作須要,做了一周時間的Rcp開發,發現由于Eclipse開發方面的中文資料較少,對入門者來說有些困難,
所以把自己一周的內容放上,共享給開始學習Eclipse開發的人
Eclipse開發中有很多名詞: 插件開發? ,RCP ,SWT,Jface很容易讓人迷糊
做個大概的比喻,如果說SWT是C++的話? 那么JFace就像STL對SWT做了簡單的封裝? Rcp就像MFC封裝更多
而插件開發和Rcp唯一不同就使導出不同,一個導出成plug in,另一個導出成獨立運行的程序。其實沒有什么區別
好了,開始第一個程序,從Hello world開始。寫到這個地方,再次崇拜一下第一個寫Hello world的人。
真應改給他搬個什么普及教育之類的獎項。
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class HelloSWT {
?public static void main(String[] args) {
??Display display = new Display();
??Shell shell = new Shell(display);
??Label label = new Label(shell, SWT.CENTER);
??label.setText("Hello, World");
??label.setBounds(shell.getClientArea());
??shell.open();
??while (!shell.isDisposed()){
??? if (!display.readAndDispatch()){
???? display.sleep();
??? }
??}
??display.dispose();
?}
}
首先介紹Display,打家都知到Swt是基于操做系統的,多大部分的控、 窗口都是調用系統的,所以得有一個東西
負責把java的消息轉變成系統消息,Display就是。
Shell可以簡單理解成就是窗口
Label就是一個標簽了。
shell.open()顯視窗口
while (!shell.isDisposed()){
? if (!display.readAndDispatch()){
?? display.sleep();
? }
}
熟悉Windows下編程的人大概都知到,Windows的消息循環機制。
好了試著運行一下這個程序,修改一下,找找感覺吧。
寫到這里忽然想起自己沒有寫如何配制SWT的開發環境,對于新手來說這個是重要的。
這里有一篇文章http://dev.yesky.com/409/2620409.shtml
如果鏈接失效的話google一下吧
說明:
這個系列的文章是基于eclipse 3.2.1的,另外推薦一些學習的資料或者網站
首先:http://www.eclipseworld.org/bbs/
然後:在上邊的論壇里邊有一些前輩們寫的教程,有些不錯值得一看
最后:當然不可少的是ibm的網站和eclipse的官方網站
======================================================================
Eclipse Rcp系列 二 第一個Rcp程序
第一個 Rcp 程序
新建 ->project->plug-in Development->plug-in project
點擊 next
?
輸入工程名 HelloRcp à next
?
其它采取默認,Rich Client Application部分選擇 yes
?
選擇 Hello Rcp à ?Finish
?
工程建立完畢,下邊選擇 MANIFEST.MF
點擊下邊的 overview 進入 overview 視圖,點擊 Launch an Eclipse application
就可以看到運行起來的界面了。就使一個簡單的窗口。
?
好,下邊如何導出能類似 Eclipse 的程序
在 HelloRcp 工程上點擊右鍵 à new à other
選擇 Product Configuration
?
在劃線部分填入 helloRcp , Finish
?
在三處分辨填入對應的內容,然後點擊 Configuration 進入 configuration 視圖
add à 選擇 HelloRcp
點擊 Add Required Plug-ins
然後點擊劃線部分,按照向導,導出成一個 Exe 工程。雙擊運行一下看看吧。
?
另外導出的這個工程和 eclipse 一樣,比如語言啦 -nl 參數,比如 jre 的設置啦 -vm
最大最小內存了,都和 eclipse 是一樣的。
好了,這個就是一個工程的過程。前兩篇文章內容很少,都是配制方面的,下邊的文章開始真的多一些內容了。
===============================================================
Eclipse Rcp系列三 進一步了解Viewer
好在二的基礎上,繼續,這個時候我們須要增加一個Viewer.在這里我須要說一下,在eclipse的開發中用到的很多
的是Viewer(視圖)這個概念,而不像Vb等開發中經常用到的window(窗口),并不是說Rcp中沒有窗口,而是使用
頻率較低,所以分別說一下如何添加窗口和Viewer
一,添加一個對話框窗口:添加一個類如下,然後在須要顯視的地方調用一下open()方法
不一定非要繼承自Dialog,這里為了漸少一些代碼,而且我使用中也多繼承自Dialog
package hellorcp;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloDialog extends Dialog {
?protected Object result;
?protected Shell shell;
?public HelloDialog(Shell parent, int style) {
??super(parent, style);
?}
?public HelloDialog(Shell parent) {
??this(parent, SWT.NONE);
?}
?public Object open() {
??createContents();
??shell.open();
??shell.layout();
??Display display = getParent().getDisplay();
??while (!shell.isDisposed()) {
???if (!display.readAndDispatch())
????display.sleep();
??}
??return result;
?}
?protected void createContents() {
??shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
??shell.setSize(500, 375);
??shell.setText("SWT Dialog");
??//
?}
}
二,添加一個viewer,首先建立一個viewer,下邊是Designer(一個很好用的插件)自動生成的一個viewer,
也就是一個Viewer的大概結構
package hellorcp;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
public class HelloView extends ViewPart {
?public static final String ID = "hellorcp.HelloView"; //$NON-NLS-1$
?public void createPartControl(Composite parent) {
??Composite container = new Composite(parent, SWT.NONE);
??//
??createActions();
??initializeToolBar();
??initializeMenu();
?}
?private void createActions() {
??// Create the actions
?}
?private void initializeToolBar() {
??IToolBarManager toolbarManager = getViewSite().getActionBars()
????.getToolBarManager();
?}
?private void initializeMenu() {
??IMenuManager menuManager = getViewSite().getActionBars()
????.getMenuManager();
?}
?public void setFocus() {
??// Set the focus
?}
}
顯視這個viewer,每個viewer須要加載到perspective上才能顯視,所以在Perspective.java中加入如下代碼
public void createInitialLayout(IPageLayout layout) {
?layout.setEditorAreaVisible(false);//不顯視edit窗口
?String editorArea = layout.getEditorArea();
?//下邊兩句的不同是,一個顯視的是單頁窗口,一個顯視的是多頁窗口
?layout.addStandaloneView(HelloViewer.ID,false, IPageLayout.LEFT, 0.25f, editorArea);
?layout.addView(HelloViewer.ID, IPageLayout.RIGHT, 0.75f, editorArea);
}
三,在viewer或者dialog上添加控件,如果裝有Designer可以直接拖放,如果沒有編程實現也可以
大部份添加到下邊這樣的函數中
viewer:
public void createPartControl(Composite parent) {
??Composite container = new Composite(parent, SWT.NONE);
??//添加一個button
??final Button delBtn = new Button(container, SWT.NONE);
??delBtn.setText("刪除");
??delBtn.setBounds(10, 83, 44, 22);
??addListener2DelBtn(delBtn);
??
??createActions();
??initializeToolBar();
??initializeMenu();
}
dialog:
protected void createContents() {
??shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
??shell.setSize(500, 375);
??shell.setText("SWT Dialog");
}?
四,響應事件,SWT的事件響應和Swing是一樣的,添加listener
delBtn.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????//加入你響應事件要做的事情
???}
});
五,布局
布局方面swt沒有什么新的地方,發個簡單使用布局的例子,參考吧.另外布局還有很多搭配,但不是本文的
重點,暫時帶過
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class TableDemo {
? /**
? * @param args
? */
? public static void main(String[] args) {
??? Display?? dispMain = new Display ();
???
??? final Shell shellMain = new Shell (dispMain, SWT.TITLE | SWT.MIN | SWT.BORDER);
???????
??? shellMain.setText("Table Demo");
???
??? FormLayout formLayout = new FormLayout();
??? formLayout.marginLeft = 10;
??? formLayout.marginRight = 10;
??? formLayout.marginTop = 10;
??? formLayout.marginBottom = 10;
??? formLayout.spacing = 10;
??? shellMain.setLayout(formLayout);
??? shellMain.setSize(800, 600);
??? Point size = shellMain.getSize();
??? Rectangle rect = dispMain.getBounds();
??? shellMain.setLocation(rect.x + (rect.width-size.x)/2, rect.y + (rect.height-size.y)/2);
??? Table demoTable = (Table)createContents(shellMain);????
??? FormData formData = new FormData();
??? formData.left = new FormAttachment(0, 0);
??? formData.top = new FormAttachment(0, 0);
??? formData.right = new FormAttachment(100, 0);
??? formData.bottom = new FormAttachment(100, -34);
??? demoTable.setLayoutData(formData);
??? Button btnClose = new Button(shellMain, SWT.PUSH | SWT.FLAT);
??? btnClose.setText("close");
???
??? formData = new FormData();
??? formData.right = new FormAttachment(100, 0);
??? formData.top = new FormAttachment(demoTable, 0);
??? formData.width = 100;
??? formData.bottom = new FormAttachment(100, 0);
??? btnClose.setLayoutData(formData);
???
??? btnClose.addSelectionListener(
??????? new SelectionListener() {
????????? public void widgetDefaultSelected(SelectionEvent e) {
??????????? this.widgetSelected(e);
????????? }
?????????
????????? public void widgetSelected(SelectionEvent e) {
??????????? shellMain.close();
????????? }
??????? }
??? );
??? shellMain.open ();
???
??? while (!shellMain.isDisposed ()) {
??????? if (!dispMain.readAndDispatch ()) {
????????? dispMain.sleep ();
??????? }
??? }
??? dispMain.dispose ();
??? dispMain = null;
? }
? /**
? *
? * @param shellMain
? * @return
? */
? private static Table createContents(Shell shellMain) {
??? Table table = new Table(shellMain, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
??? table.setHeaderVisible(true);
??? table.setLinesVisible(true);
??? table.setFont(new Font(shellMain.getDisplay(), "Arial", 11, SWT.BOLD));
???
??? TableColumn colNumber = new TableColumn(table, SWT.NONE);
??? TableColumn colMedName = new TableColumn(table, SWT.CENTER);
??? TableColumn colPrice = new TableColumn(table, SWT.CENTER);
??? TableColumn colUnit = new TableColumn(table, SWT.CENTER);
??? TableColumn colCount = new TableColumn(table, SWT.CENTER);
???
??? colNumber.setWidth(25);
???
??? colMedName.setWidth(150);
??? colMedName.setText("Medicine Name");
???
??? colPrice.setWidth(150);
??? colPrice.setText("Medicine Price");
???
??? colUnit.setWidth(150);
??? colUnit.setText("Medicine Unit");
???
??? colCount.setWidth(150);
??? colCount.setText("Medicine Count");
???
??? for(int i=0; i<10; i++) {
??????? TableItem item = new TableItem(table, SWT.NONE);
??????? item.setText(new String[]{i+1+"","4/2","4/3","4/4","4/5","4/6","4/7","4/8","4/9"});
??? }
??? return table;
? }
}
五,加入 右鍵 ,雙擊
加入兩個listener
//右鍵
private void hookContextMenu() {
??MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
??menuMgr.setRemoveAllWhenShown(true);
??menuMgr.addMenuListener(new IMenuListener() {
???public void menuAboutToShow(IMenuManager manager) {
????HelloView.this.fillContextMenu(manager);
???}
??});
??Menu menu = menuMgr.createContextMenu(viewer.getControl());
??viewer.getControl().setMenu(menu);
??getSite().registerContextMenu(menuMgr, viewer);
}
private void fillContextMenu(IMenuManager manager) {
??manager.add(addAction);
??manager.add(modifyAction);
??manager.add(deleteAction);
??manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
//雙擊
private void hookDoubleClickAction() {
??viewer.addDoubleClickListener(new IDoubleClickListener() {
???public void doubleClick(DoubleClickEvent event) {
????//doubleClickAction.run();
???}
??});
}
六,使用TableViewer
Jface中封裝了talbeViewer TreeViewer等控件,能簡單的實現很多功能,首先說說TableView
//SWT.FULL_SELECTION 可以選中一整行
//SWT.MULTI 可以選中多行
viewer = new TableViewer(wareListGroup, SWT.BORDER | SWT.FULL_SELECTION
????| SWT.MULTI);
??final Table table = viewer.getTable();
??table.setHeaderVisible(true);//顯視表頭
??table.setLinesVisible(true);//顯視表格
??
??//實現點擊表頭自動重新排序
??final TableColumn num = new TableColumn(table, SWT.NONE);
??num.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????resetSort(WareViewerSort.NUM);
????//resetSort是自己實現的重新排序的函數,只須要把不通的ViewerSort重新設置給
????TableViewer,并刷新
???}
??});
??num.setAlignment(SWT.CENTER);
??num.setWidth(50);
??//這個地方使用了message,只要做過國際話的大概都能明白
??num.setText(Messages.getString("HelloView.warenum")); //$NON-NLS-1$
??final TableColumn name = new TableColumn(table, SWT.NONE);
??name.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????resetSort(WareViewerSort.NAME);//同上
???}
??});
??name.setWidth(80);
??name.setText(Messages.getString("WareView.warename")); //$NON-NLS-1$
??name.setAlignment(SWT.CENTER);
??
??final TableColumn desc = new TableColumn(table, SWT.NONE);
??desc.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????resetSort(WareViewerSort.DESC);
???}
??});
??desc.setWidth(110);
??desc.setText(Messages.getString("WareView.waredesc")); //$NON-NLS-1$
??final TableColumn price = new TableColumn(table, SWT.NONE);
??price.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????resetSort(WareViewerSort.PRICE);
???}
??});
??price.setWidth(70);
??price.setText(Messages.getString("WareView.wareprice")); //$NON-NLS-1$
??price.setAlignment(SWT.RIGHT);
??final TableColumn updDate = new TableColumn(table, SWT.NONE);
??updDate.addSelectionListener(new SelectionAdapter() {
???public void widgetSelected(SelectionEvent e) {
????resetSort(WareViewerSort.UPDDATE);
???}
??});
??updDate.setWidth(150);
??updDate.setText(Messages.getString("WareView.wareupddate")); //$NON-NLS-1$
??updDate.setAlignment(SWT.CENTER);
??//一個TableViewer里邊的數據變動主要取決于下邊四句
??viewer.setContentProvider(new WareContentProvider()); //表的顯視
??viewer.setLabelProvider(new WareLabelProvider());??? //表的數據提供者
??viewer.setInput(//真實的數據來源); //數據來源例如ArrayList等
??viewer.setSorter(new WareViewerSort()); //排序
??
兩個provider的實現類似下邊的情況??
class WareContentProvider implements IStructuredContentProvider {
??public Object[] getElements(Object inputElement) {
???if (inputElement instanceof Node) {
????ArrayList list = new ArrayList();
????makeWareList(((Node) inputElement), list);
????return list.toArray();
???}
???if (inputElement instanceof List) {
????return ((List) inputElement).toArray();
???}
???return null;
??}
??public void dispose() {
???// TODO Auto-generated method stub
??}
??public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
???// TODO Auto-generated method stub
??}
?}
class WareLabelProvider extends LabelProvider implements
???ITableLabelProvider {
??public Image getColumnImage(Object element, int columnIndex) {
???// TODO Auto-generated method stub
???return null;
??}
??public String getColumnText(Object element, int columnIndex) {
???if (element instanceof Ware) {
????switch (columnIndex) {
????case 0:
?????return ((Ware) element).getDisplayNum();
????case 1:
?????return ((Ware) element).getDisplayName();
????case 2:
?????return ((Ware) element).getDisplayDesc();
????case 3:
?????return ((Ware) element).getDisplayPrice();
????case 4:
?????return ((Ware) element).getDisplayUpdDate();
????default:
?????break;
????}
???}
???return null;
??}
?}
===========================================================
?
Eclipse Rcp系列 四 彈出提示窗口
如何實現各式各樣的提示窗口呢,SWT提供了一個類
MessageDialog
只有一個確定
MessageDialog.openInformation(shell, "title", "message");
有是/否
MessageDialog.openConfirm(shell, "title","message");
有是/否/取消
MessageDialog dialog = new MessageDialog(shell, "title", null, "message",
??MessageDialog.QUESTION, new String[] {IDialogConstants.YES_LABEL,
??IDialogConstants.NO_LABEL,IDialogConstants.CANCEL_LABEL }, 0);
dialog.open();
還可以加入更多的選擇項,只需要在數組中加入更多的內容
那如何取得點擊了哪個按鈕呢,兩種方法
直接int result = dialog.open();
或者int result = dialog.getReturnCode();
返回的result的值就是被選中按鈕在數組中的index
=======================================================================
Eclipse Rcp系列 5 開發過程中遇到的小問題合集
這些小問題會影響開發,查找這些問題還是比較耗時間的,這里把我在學習過程中遇到的問題,找到答案中比較好的轉出來。
1,使用第三方控件,在Rcp開發中使用第三方控件(lib)的方式和一般的開發不太一樣,方式如下鏈接
http://www.javazy.com/contentex/200644225825.shtml
2,使用屬性文件,對於屬性文件的讀取,也稍有不同,使用方法(轉自http://blog.csdn.net/explorering/archive/2006/10/11/1330709.aspx)
1。使用java.util.Properties類的load()方法?
示例:?
InputStream?in?=?lnew?BufferedInputStream(new?FileInputStream(name));?
Properties?p?=?new?Properties();?
p.load(in);?
2。使用java.util.ResourceBundle類的getBundle()方法?
示例:
ResourceBundle?rb?=?ResourceBundle.getBundle(name,?Locale.getDefault());?
3。使用java.util.PropertyResourceBundle類的構造函數?
示例:?
InputStream?in?=?new?BufferedInputStream(new?FileInputStream(name));?
ResourceBundle?rb?=?new?PropertyResourceBundle(in);?
4。使用class變量的getResourceAsStream()方法?
示例:?
InputStream?in?=?JProperties.class.getResourceAsStream(name);?
Properties?p?=?new?Properties();?
p.load(in);?
5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法?
示例:?
InputStream?in?=?JProperties.class.getClassLoader().getResourceAsStream(name);?
Properties?p?=?new?Properties();?
p.load(in);?
6。使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法?
示例:?
InputStream?in?=?ClassLoader.getSystemResourceAsStream(name);?
Properties?p?=?new?Properties();?
p.load(in);?
補充?
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法?
示例:
InputStream?in?=?context.getResourceAsStream(path);?
Properties?p?=?new?Properties();?
p.load(in);?
3,國際化,在國際化界面的同時,記得國際化plug-in,國際話的方法 不同于程序中的Message.getString()方法,是使用的%,這樣
?<view
??????????? class="com.niis.myprice.views.KindView"
??????????? id="com.niis.myprice.views.KindView"
??????????? name="%plugin.kindmanager"/>
然後對應各種語言建立一個plugin.properties,記著發布的時候不要忘記加入這些配制文件。
===========================================================================
Eclipse Rcp系列 六 TreeView
treeView的使用和TableView差不多,不同的是ContentProvider和LabelProvider的實現接口不同了。下邊是個例子,看一下相信你就,明白了
?class KindLabelProvider extends LabelProvider {
??public String getText(Object obj) {
???if (obj instanceof Kind) {
????return obj.toString();
???}
???return null;
??}
??public Image getImage(Object obj) {
???// String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
???if (obj instanceof Kind) {
????String imageKey = ISharedImages.IMG_OBJ_FOLDER;
????PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
???}
???return null;
??}
?}
?class KindContentProvider implements IStructuredContentProvider,
???ITreeContentProvider {
??public Object[] getElements(Object parent) {
???if(parent instanceof Kind){
????return getChildren(parent);
???}
???return null;
??}
??public Object getParent(Object child) {
???if (child instanceof Node) {
????return ((Node) child).getParent();
???}
???return null;
??}
??public Object[] getChildren(Object parent) {
???if (parent instanceof Kind) {
????ArrayList children = ((Kind) parent).getChildren();
????
????return children.toArray(new Node[children.size()]);
????
???}
???return new Object[0];
??}
??public boolean hasChildren(Object parent) {
???if (parent instanceof Kind)
????return ((Kind) parent).hasChildren();
???return false;
??}
??public void dispose() {
???// TODO Auto-generated method stub
??}
??public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
???// TODO Auto-generated method stub
??}
?}
====================================================================
Eclipse Rcp系列 七 多線程
Eclipse中多線程的實現,類似這樣
Job job = new Job("job1") {
?protected IStatus run(IProgressMonitor monitor) {
??//-----你自定義的東西
??Job1 job1 = new Job1();
??job1.run();
??//-----------------
??return Status.OK_STATUS;
?}
};
job.setPriority(Job.SHORT);
job.schedule();? //start as soon as possible
================================================
Eclipse Rcp 系列八 中更改狀態條的信息
Eclipse Rcp中更改狀態條的信息
private void showStatusMessage(String msg) {
??WorkbenchWindow workbenchWindow = (WorkbenchWindow) PlatformUI
????.getWorkbench().getActiveWorkbenchWindow();
???workbenchWindow.setStatus(msg);
?}
=====================================================
前一段時間學習eclipse rcp開發寫的一個學習用的工程。涉及了我當時學到的一些方面。
當時想找一個可以用來學習的簡單的源代碼真難,有的都是復雜的。
這里提供一個簡單的工程。設計初學者接觸的各種問題。有時通一件事情使用了兩種方式來實現。
使用了treeview? ,tableview?
tableview的排序
加入了javamail
使用了jobs后臺進程
加入了log4j
國際化
設置了部署工程
右鍵、菜單、雙擊等事件
Source CODE
總結
以上是生活随笔為你收集整理的Eclipse Rcp系列 http://www.blogjava.net/dreamstone/archive/2007/02/08/98706.html的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA 语言学习
- 下一篇: 第一个Ajax.net程序的实现及心得。