一、搭建开发环境[eclipse3.5.2的plugins目录中有以下jar包]
1. swt 环境[如仅仅是swt编程只要下面一个jar包]:
org.eclipse.swt.win32.win32.x86_3.5.2.v3557f.jar
2. jface环境[如程序中需要使用到jface中的控件等,需要增加以下jar包]:
org.eclipse.jface_3.5.2.M20100120-0800.jar
org.eclipse.core.commands_3.5.0.I20090525-2000.jar
org.eclipse.equinox.common_3.5.1.R35x_v20090807-1100.jar
二、开发第一个SWT应用
HelloWorld源代码
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloWorld {
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setText("第一个SWT程序");
shell.setSize(new Point(300, 200));
shell.setLayout(new GridLayout());
//......
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
HelloWorld另一种写法
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloWorld {
private Shell shell = null;
private void createShell() {
shell = new Shell();
shell.setText("第一个SWT程序");
shell.setSize(new Point(300, 200));
shell.setLayout(new GridLayout());
}
public static void main(String[] args) {
Display display = Display.getDefault();
HelloWorld thisClass = new HelloWorld();
thisClass.createShell();
thisClass.shell.open();
while (!thisClass.shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
三、程序解释
四、增加一个按钮并给该按钮增加事件
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloWorld {
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setText("第一个SWT程序");
shell.setSize(new Point(300, 200));
shell.setLayout(new GridLayout());
Button button = new Button(shell, SWT.NONE);
button.setText("hello");
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("点击了hello按钮...");
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
《ECLIPSE从入门到精通》 陈刚 著 读书笔记