Eclipse插件开发3-SWT基础

        SWT相对于SWING对于资源的消耗等都做了好多的优化,性能提升很多,下面介绍怎样创建一个简单的SWT应用。

       首先如果你不需要可视化编辑的话,确认eclipse的plugins文件下有SWT相关的JAR包。如果你想做可视化拖拽式的界面开发 ,你还需要在eclipse->help->install new software中下拉框中选择(我的是Mars - ttp://download.eclipse.org/releases/mars),然后输入SWT就可以进行安装了,当然前提是必须要能上网,如果不能上网,就去下载离线版的安装,记得选择与你的eclipse兼容的。

       下面的将用可视化方式编写一个最简单的SWT窗口

        新建一个swt project,然后新建一个SWT application,在打开的编辑器中选择designer,从左边工具箱拖进一个 composite  然后拖一个TEXT和一个BUTTON进去,双击BUTTON会进入源码,自动生成了button的单击事件,我们暂且在里面输入MessageBox box = new MessageBox(shell);
    box.setMessage("text文本的内容是:"+text.getText());
    box.open(); 然后点击右键运行 ,在TEXT输入任意内容,点击button就会弹出相应的提示内容

 

 以下是源代码,很多都是自动生成的

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class testSWT {

 protected Shell shell;
 private Text text;

 /**
  * Launch the application.
  * @param args
  */
 public static void main(String[] args) {
  try {
   testSWT window = new testSWT();
   window.open();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * Open the window.
  */
 public void open() {
  //生成Display对象(1)
  Display display = Display.getDefault();
  createContents();
  //打开shell对象(7)
  shell.open();
  shell.layout();
  //结束前一直循环(8)
  while (!shell.isDisposed()) {
   if (!display.readAndDispatch()) {
    display.sleep();
   }
  }
  //释放dispaly对象(9)
  display.dispose();
 }

 /**
  * Create contents of the window.
  */
 protected void createContents() {
  //生成Display对象(2)
  shell = new Shell();
  shell.setSize(450, 300);
  shell.setText("SWT Application");
  
  //生成Composite容器对象(3)
  Composite composite = new Composite(shell, SWT.NONE);
  composite.setBounds(10, 10, 424, 252);
  //生成Text对象(4)
  text = new Text(composite, SWT.BORDER);
  text.setBounds(10, 10, 71, 23);
  //生成Button对象(5)
  Button btnButton = new Button(composite, SWT.NONE);
  //为BUTTON对象添加监听器(6)
  btnButton.addSelectionListener(new SelectionAdapter() {
   @Override
   public void widgetSelected(SelectionEvent e) {
    MessageBox box = new MessageBox(shell);
    box.setMessage("text文本的内容是:"+text.getText());
    box.open();
   }
  });
  btnButton.setBounds(104, 6, 80, 27);
  btnButton.setText("button");

 }
}

(8)处的代码:因为SWT应用启动了一个新的线程,如果不阻塞主线程的话 ,应用就会结束了,我们就看不到窗口了 ,所以在用了一个循环 ,这些都是SWT自动生成的

(9)是我加上的,小的测试应用上不加没什么问题,但要养成一个良好的习惯,主动释放display,display会同时释放它的子空间的资源,但类似 COLOR等一些资源是要自己释放的。

以上所有的代码你也可以不用可视化开发,完全可以手动创建一个普通的JAVA类,输入以上的所有内容,也是完全可以的

  

     

猜你喜欢

转载自zrgzrgzrgzrg.iteye.com/blog/2274239