??xml version="1.0" encoding="utf-8" standalone="yes"?> 原来在静态代码块上出CException,造成在运行main函数之前退Z。所以才说没有main函数?br>我们知道classload在加载一个类的时候,对于静态代码块会逐行执行Q按照出现的先后序。同时父cȝ静态代码块一定比子类的先执行。因?br>在load子类之前会先load父类。这是Z么hello world中不会出现问题,q里会出现问题的原因。因为Dialog比ApplicationWindow多了q段静态代码?/p>
l箋q下Mؓ什么这D代码会出现I指针异常呢Q原来这D代码依赖于new Shell()必须先运行。而我们的new Shell()写在mainҎ里边Q肯定是在加载类完成后才能运行的。所以在cd部直接写个mainҎ是不行的。只能单独写个类来调用?br>Ҏ二: 2Q这四个的不同之处有三点Q?br> 提示的图标?nbsp; 昄的按钮?nbsp; q回?br>openInfomation cMi的图?nbsp; 一个确?nbsp; void 最后说一下,MessageDialog的大不能根据内容自动调_对于量提示信息的时候显得大了些?br>3QInputDialog输入的dialog 做过SWT开发的人对q种格式应该不陌生,到处都是?br> 按钮的组合:
http://www.aygfsteel.com/Files/dreamstone/eclipse1.part2.rar
http://www.aygfsteel.com/Files/dreamstone/eclipse1.part3.rar
http://www.aygfsteel.com/Files/dreamstone/eclipse1.part4.rar
http://www.aygfsteel.com/Files/dreamstone/eclipse1.part5.rar
http://www.aygfsteel.com/Files/dreamstone/eclipse1.part6.rar
调用q个接口的refreshLocalҎ卛_。例如refreshLocal(IResource.DEPTH_INFINITE, null)
2、到底有哪些cdCq个接口?
来看一下承结?br>首先l承自IResource的接口有IContainer、IFolder、IProject、IWorkspaceRoot、IFile一??br>加上IResource 6个,凡是实现q些接口的都可以?br>3、接口的l承l构
接口 extends
IResource ?nbsp;
IContainer IResource
IFile IResource
IFolder IContainer
IProject IContainer
IWorkspaceRoot IContainer
4、类的承结?/span>
c?nbsp; extends implements
Resource ?nbsp; IResource
Container Resource IContainer
File Resource IFile
Folder Container IFolder
Project Container IProject
WorkspaceRoot Container IWorkspaceRoot
二、实现重~译(也就是clean)
clean all:
ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.CLEAN_BUILD,
monitor);
clean one project
((IProject) selection[i]).build(IncrementalProjectBuilder.CLEAN_BUILD, new
SubProgressMonitor(monitor, 1));
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class TestProgress
{
static boolean stopflg = false;
/** *//**
* Launch the application
* @param args
*/
public static void main(String[] args) throws Exception
{
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(500, 375);
shell.setText("SWT Application");
//
IRunnableWithProgress runnable = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
monitor.beginTask("generate", 30);
for(int i=0;i<100;i++)
{
if(monitor.isCanceled())
{
return;
}
monitor.worked(1);
Thread.sleep(50);
}
monitor.done();
}
};
new ProgressMonitorDialog(shell).run(true, true, runnable);
shell.open();
shell.layout();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
}
}
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class TestProgress
{
static boolean stopflg = false;
/** *//**
* Launch the application
* @param args
*/
public static void main(String[] args) throws Exception
{
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(500, 375);
shell.setText("SWT Application");
//
IRunnableWithProgress runnable = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
monitor.beginTask("generate", 30);
int i=0;
while(true)
{
if(stopflg)
{
break;
}
i++;
if(i==30)
{
i=0;
monitor.beginTask("generate", 30);
}
monitor.worked(1);
Thread.sleep(100);
}
monitor.done();
}
};
new ProgressMonitorDialog(shell).run(true, true, runnable);
shell.open();
shell.layout();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
}
}
public void saveState()
{
if (text.getText() == null || text.getText().equals(""))
{
return ;
}
IDialogSettings topSettings = getTopSettings();
IDialogSettings settings = topSettings.getSection("TestDialog");
if(settings == null)settings = topSettings.addNewSection("TestDialog");
settings.put("value", text.getText());
try
{
topSettings.save("content/system.xml");
}catch(IOException e)
{
System.out.println(e.getMessage());
}
}
public void restoreState()
{
IDialogSettings topSettings = getTopSettings();
IDialogSettings settings = topSettings.getSection("TestDialog");
if(settings == null) return;
if (text.getText() == null || text.getText().equals(""))
{
text.setText(settings.get("value"));
}
}
public IDialogSettings getTopSettings()
{
IDialogSettings topSettings = new DialogSettings("system");
try
{
topSettings.load("content/system.xml");
}catch(IOException e)
{
System.out.println(e.getMessage());
}
return topSettings;
}
然后在覆写的buttonPressed函数中调用save
protected void buttonPressed(int button)
{
saveState();
}
protected Control createDialogArea(Composite parent)
{
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new RowLayout());
text = new Text(container, SWT.BORDER);
text.setLayoutData(new RowData(100,-1));
//加入q一?/span>
if (text.getText() == null || text.getText().equals(""))
{
restoreState();
}
return container;
}
source下蝲:http://www.aygfsteel.com/Files/dreamstone/jface-record.rar
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Shell;
public class TestDialog extends Dialog
{
public TestDialog(Shell parentShell)
{
super(parentShell);
}
}
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Test
{
public static void main(String[] args)
{
Shell shell = new Shell();
TestDialog td = new TestDialog(shell);
td.setBlockOnOpen(true);
td.open();
Display.getCurrent().dispose();
}
}
二、看C边的代码是否会想到别的呢Qؓ什么要再写一个类来运行Dialog,不能在内部写个mainҎ吗?
我们来试一下:
Ҏ一Q参考Jface hello world的的写法:
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class TestDialog extends Dialog
{
public TestDialog(Shell parentShell)
{
super(parentShell);
}
public static void main(String[] args)
{
TestDialog td = new TestDialog(new Shell());
td.setBlockOnOpen(true);
td.open();
Display.getCurrent().dispose();
}
}
q行一下看看什么效果,提示找不到mainҎ。且打印出如下Exception
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:184)
at org.eclipse.jface.resource.JFaceResources.getImageRegistry(JFaceResources.java:310)
at org.eclipse.jface.dialogs.Dialog.<clinit>(Dialog.java:211)
Exception in thread "main"
Z么呢Q我们是有mainҎ的,跟进Exceptionȝ看吧?br>发现问题出现在Dialogcȝq段代码?
static
{
ImageRegistry reg = JFaceResources.getImageRegistry();
reg.put(DLG_IMG_MESSAGE_INFO, ImageDescriptor.createFromFile(
Dialog.class, "images/message_info.gif")); //$NON-NLS-1$
reg.put(DLG_IMG_MESSAGE_WARNING, ImageDescriptor.createFromFile(
Dialog.class, "images/message_warning.gif")); //$NON-NLS-1$
reg.put(DLG_IMG_MESSAGE_ERROR, ImageDescriptor.createFromFile(
Dialog.class, "images/message_error.gif")); //$NON-NLS-1$
}
单独写个cd下:import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Test
{
public static void main(String[] args)
{
TestDialog td = new TestDialog(new Shell());
td.setBlockOnOpen(true);
td.open();
Display.getCurrent().dispose();
}
}
三、去掉两个按?br>虽然Dialog天生带的两个按钮不错Q但我们有的时候ƈ不想要这两个按钮Q怎么办,如何L它?
单,只要我们覆盖父类的createButtonsForButtonBarq个Ҏ可以了Q覆写这个方法,里边什么也不写
protected void createButtonsForButtonBar(Composite parent)
{
}
看一下按钮消׃?br>四、加入右上角的最大化和关?br>覆写父类的这个方法:
protected int getShellStyle()
{
return super.getShellStyle()|SWT.RESIZE|SWT.MAX;
}
五、改变Dialog的大?br>覆写q个ҎQ?br>
protected Point getInitialSize()
{
return new Point(300,400);//300是宽400是高
}
覆写createDialogAreaҎ
protected Control createDialogArea(Composite parent)
{
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new RowLayout());
text = new Text(container, SWT.BORDER);
text.setLayoutData(new RowData(100,-1));
return container;
}
q里使用了RowLayout
七、加入自q按钮
覆写initializeBounds
protected void initializeBounds()
{
Composite comp = (Composite)getButtonBar();
super.createButton(comp, IDialogConstants.OK_ID, "完成", true);
}
使用Ҏ和前边相同,不同的是不是l承自Dialog而是l承自TitleAreaDialogQ然后在createDialogArea中加入两?br>
setTitle("标题");
setMessage("提示信息")
//setMessage可以加上囄Q加入的办法是setMessage("提示信息",IMessageProvider.WARNING);如果惛_入其他的囄Q调用相应的帔R?/span>
source下蝲:http://www.aygfsteel.com/Files/dreamstone/jface-dialog.rar
一、MessageDialog
1,MessageDialog的用法很单,只需要一句话.
MessageDialog.openInfomation(shell,title,message);
MessageDialog.openConfirm(shell,title,message);
MessageDialog.openQuestion(shell,title,message);
MessageDialog.openError(shell,title,message);
openConfirm 问号图标 定和取?nbsp; boolean
openQuestion 问号图标 是和?nbsp; boolean
openError 一个X的图?nbsp; 定 void
使用ҎQ?/p>
InputDialog inputDialog = new InputDialog(shell,"标题","提示信息","默认?/span>",null);
if(inputDialog.open() == InputDialog.OK)
{
String value = dialog.getValue();
}
public class MyValidator implements IInputValidaor
{
public String isValid(String newText)
{
float value = 0;
try
{
value = Float.valueOf(newText).floatValue();
}catch(NumberFormatException e)
{
return "错误:误入数?/span>";
}
if(value>0 && value<100)
{
return null;
}else
{
return "错误Q请输入大于0Q小?00的数";
}
}
}
然后改写定义语句?br>
InputDialog inputDialog = new InputDialog(shell,"标题","提示信息","默认?/span>",new MyValidator());
同样l承自Dialog.
1,使用ҎQMessageBox的用方法稍微复杂,需??
MessageBox mb = new MessageBox(shell);
mb.setMessage("提示信息");
mb.open();
是通过new的时候加入式h实现的,例如
MessageBox mb = new MessageBox(shell,SWT._ICON_QUEST|SWT.YES|SWT.NO);
图标的种c:
SWT.ICON_ERROR
SWT.ICON_INFORMATION
SWT.ICON_QUESTION
SWT.ICON_WARNING
SWT.OK
SWT.OK|SWT.CANCEL
SWT.YES|SWT.NO
SWT.YES|SWT.NO|SWT.CANCEL
SWT.RETRY|SWT.CANCEL
SWT.ABORT|SWT.RETRY|SWT.IGNORE
仔细看一下就是我们^时经常看到的各种对话框?br>三、颜色选择对话?br>不多_使用Ҏ几乎在swt中遍地都是的用法?br>ColorDialog dialog = new ColorDialog(shell);
RGB rgb = dialog.open();
if(rgb != null)
{
Color color = new Color(shell.getDisplay(),rgb);
}
注意color使用q后要dispose();
四、字体选择对话?br>有了上边的一些经验其实在有eclipseq种~辑器的帮助下猜着可以写?br>
FontDialog dialog = new FontDialog(shell);
FontData fontData = dialog.open();
if (fontDate != null)
{
Font font = new Font(shell.getDisplay(),fontData);
}
同样在结束后font.dispose();
五、打印对话框Q同上的使用ҎQ同上的需要dispose
PrintDialog dialog = new PrintDialog(shell);
PrintData printData = dialog.open();
if (printDate != null)
{
Printer printer = new Printer(printerData);
}
六、文仉择对话框:同上
1Q实现方?br>
FileDialog dialog = new FileDialog(shell,SWT.OPEN);
dialog.setFilterPath("c:\windows");//讄初始路径
String fileName = dialog.open();//q回的全路径(路径+文g?
FileDialog dialog = new FileDialog(shell,SWT.OPEN|SWT.MULTI);
String fileName = dialog.open();//q回最后一个选择文g的全路径
String[] fileNames = dialog.getFileNames();//q回所有选择的文件名Q不包括路径
String path = dialog.getFilterPath();q回选择的\径,q个和fileNames配合可以得到所有的文g的全路径
FileDialog dialog = new FileDialog(shell,SWT.OPEN|SWT.NULTI);
dialog.setFilterNames(new String[]
{"可执行文?*.exe),"Excel(*.xls),"所有文?/span>""});
dialog.setFilterExtensions(new String[]
{"*.exe","*.xls","*.*"});
//接受Ҏ?中的写法Q不同就是加入了qo器?/span>
FileDialog dialog = new FileDialog(shell,SWT.SAVE);
String fileName = dialog.open();
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class TestListViewer
{
static class ListLabelProvider extends LabelProvider
{
public String getText(Object element)
{
Country country = (Country)element;
return country.getName();
}
public Image getImage(Object element)
{
return null;
}
}
static class ContentProvider implements IStructuredContentProvider
{
public Object[] getElements(Object inputElement)
{
if(inputElement instanceof List)
{
List list = (List)inputElement;
return list.toArray();
}
return new Object[0];
}
public void dispose()
{
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
}
static class Country
{
private String name;
public Country()
{
}
public Country(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public static List getCountryList()
{
List list = new ArrayList();
list.add(new Country("中国"));
list.add(new Country("国"));
list.add(new Country("日本"));
return list;
}
}
private static org.eclipse.swt.widgets.List list;
/** *//**
* Launch the application
* @param args
*/
public static void main(String[] args)
{
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(500, 375);
shell.setText("SWT Application");
//
shell.open();
final ListViewer listViewer = new ListViewer(shell, SWT.BORDER);
listViewer.setLabelProvider(new ListLabelProvider());
listViewer.setContentProvider(new ContentProvider());
listViewer.setInput(new Object());
list = listViewer.getList();
list.setBounds(122, 63, 100, 100);
listViewer.setContentProvider(new ContentProvider());
listViewer.setLabelProvider(new ListLabelProvider());
listViewer.setInput(Country.getCountryList());
//可以直接d
listViewer.add(new Country("英国"));
shell.setLayout(new FillLayout());
shell.layout();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
}
}
二、注意代码的注释部分Q可以直接添加和U除?
错误二:
按照教程的操作,l果出现错误
org.eclipse.ui.PartInitException: Unable to open editor, unknown editor ID:
查你的plugin.xml中的q一D?br><extension
point="org.eclipse.ui.editors">
<editor
class="gef.tutorial.step.ui.DiagramEditor"
default="false"
icon="icons/alt_about.gif"
id="gef.tutorial.step.ui.DiagramEditor"
name="Diagram Editor"/>
</extension>
是否有icon=""Q我开始以为没有icon没什么所以没配置Q结果一直出错,配上好了。感觉这个做的真
让h郁闷Q还必须有icon
1,Ctrl+D 删除选中的几?br>2,Alt+上下头 Ud选中的代码块
3,Alt+左右头 回退 前进
4,Alt+Shift+上下头 复制选中的代码块
5,sysout+Ctrl space 生成System.out.println();
6,main + Ctrl space 生成最单的main函数
7,Ctrl+Shift+X 切换成大?br>8,Ctrl+Shift+Y 切换成小?br>9,Ctrl+Z 取消undo
10,Ctrl+Y redo
11,Ctrl+S 保存
12,Tab 块羃q?br>13,Shift+Tab 反向块羃q?br>14,Ctrl+Shif+F 格式化代?br>15,Ctrl+O 昄成员Ҏ ,成员对象
16,Ctrl+Shift+I 调试的时候显C对象的?br>17,Ctrl+M 全屏
18,Ctrl+N 新徏
19,Ctrl+L q入到第N?br>20,Ctrl+/ 注释打开代码
21,Ctrl+Shift+/ 块注?br>22,Ctrl+Shift+\ 块注释取?br>23,Ctrl+1 U正代码
24,F3 昄l承?br>25,Ctrl+F 查找替换
26,Ctrl+H 更大范围的查找替?br>27,F5 Step into
28,F6 Step over
29,F7 Step return
30,F8 resume
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
}
}
一Q添加一个对话框H口Q添加一个类如下Q然後在要显视的地方调用一下open()Ҏ
不一定非要承自Dialog,q里Z渐少一些代?而且我用中也多l承自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");
//
}
}
二,d一个viewerQ首先徏立一个viewer,下边是DesignerQ一个很好用的插Ӟ自动生成的一个viewerQ?br>也就是一个Viewer的大概结?br>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
}
}
显视q个viewer,每个viewer要加蝲到perspective上才能显视,所以在Perspective.java中加入如下代?br>public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(false);//不显视editH口
String editorArea = layout.getEditorArea();
//下边两句的不同是Q一个显视的是单늪口,一个显视的是多늪?br> layout.addStandaloneView(HelloViewer.ID,false, IPageLayout.LEFT, 0.25f, editorArea);
layout.addView(HelloViewer.ID, IPageLayout.RIGHT, 0.75f, editorArea);
?/p>
三,在viewer或者dialog上添加控Ӟ如果装有Designer可以直接拖放Q如果没有编E实C可以
大部份添加到下边q样的函C
viewer:
public void createPartControl(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
//d一个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");
}
四,响应事g,SWT的事件响应和Swing是一LQ添加listener
delBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
//加入你响应事件要做的事情
}
});
五,布局
布局斚wswt没有什么新的地方,发个单用布局的例子,参考吧.另外布局q有很多搭配Q但不是本文?br>重点Q暂时带q?br>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;
}
}
五,加入 右键 Q双?br>加入两个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{控Ӟ能简单的实现很多功能Q首先说说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重新讄l?br> TableViewerQƈh
}
});
num.setAlignment(SWT.CENTER);
num.setWidth(50);
//q个地方使用了messageQ只要做q国际话的大概都能明?br> 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()); //表的数据提供?/p>
viewer.setInput(//真实的数据来?; //数据来源例如ArrayList{?br> viewer.setSorter(new WareViewerSort()); //排序
两个provider的实现类g边的情况
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;
}
}
新徏 ->project->plug-in Development->plug-in project
点击 next
输入工程?/span> HelloRcp à next
选择 Hello Rcp à Finish
工程建立完毕Q下辚w择 MANIFEST.MF
点击下边?/span> overview q入 overview 视图Q点?/span> Launch an Eclipse application
可以看到运行v来的界面了。就使一个简单的H口?/span>
好,下边如何导出能类?/span> Eclipse 的程?/span>
?/span> HelloRcp 工程上点d?/span> à new à other
选择 Product Configuration
在三处分辨填入对应的内容Q然後点?/span> Configuration q入 configuration 视图
add à 选择 HelloRcp
点击 Add Required Plug-ins
然後点击划线部分Q按照向|导出成一?/span> Exe 工程。双击运行一下看看吧?/span>
另外导出的这个工E和 eclipse 一P比如语言?/span> -nl 参数Q比?/span> jre 的设|啦 -vm
最大最内存了Q都?/span> eclipse 是一L?/span>
好了Q这个就是一个工E的q程。前两篇文章内容很少Q都是配制方面的Q下边的文章开始真的多一些内容了?/span>
好了Q开始第一个程?从Hello world开始。写到这个地方,再次崇拜一下第一个写Hello world的h?br>真应改给他搬个什么普及教育之cȝ奖项?br>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();
}
}
首先介绍DisplayQ打安知到Swt是基于操做系l的Q多大部分的控?H口都是调用pȝ的,所以得有一个东?br>负责把java的消息{变成pȝ消息QDisplay是?/p>
Shell可以单理解成是H口
Label是一个标{了?/p>
shell.open()显视H口
while (!shell.isDisposed()){
if (!display.readAndDispatch()){
display.sleep();
}
}
熟悉Windows下编E的人大概都知到QWindows的消息@环机制?/p>
好了试着q行一下这个程序,修改一下,找找感觉吧?/p>
写到q里忽然惌v自己没有写如何配制SWT的开发环境,对于新手来说q个是重要的?br>q里有一文?a >http://dev.yesky.com/409/2620409.shtml
如果链接失效的话google一下吧
说明Q?br>q个pd的文章是Zeclipse 3.2.1的,另外推荐一些学习的资料或者网?br>首先Q?a >http://www.eclipseworld.org/bbs/
然後Q在上边的论坛里Ҏ一些前辈们写的教程Q有些不错值得一?br>最后:当然不可的是ibm的网站和eclipse的官方网?/p>