love fish大鹏一曰同风起,扶摇直上九万里

常用链接

统计

积分与排名

friends

link

最新评论

Swt常用控件中文教程(转)

(样图没有贴上,不好意思)
1、Eclipse中swt的配置
建议配置:jdk1.4.2以及eclipse3.1
在代码中调用swt控件之前,首先建立一个项目,然后选择该项目的properties -> Java Build Path,将standard Widget ToolKit加入到Library页当中。如下图所示:
 接下来可以建立第一个eclipse小程序,新建一个class,并且在该class所对应的代码中输入如下程序,其中package以及class名称根据实际情况来确定名称。
package mypakage;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
/*导入需要的类库*/
public class Myfrm1 {
public Myfrm1() {
super();
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
/*shell为一个窗口对象*/
Label label = new Label(shell, SWT.NONE);
label.setText("Hello, World!");  /*创建一个标签对象并且设置标题文字*/
label.pack();
shell.pack();
shell.open();  /*打开并显示窗口*/
while(!shell.isDisposed())
if(!display.readAndDispatch())
    display.sleep();  /*在窗口没有销毁之前,显示对象一直处于等待状态*/

display.dispose();  /*否则,销毁对象,释放对象所占据的资源*/
label.dispose();
}
}
运行上述代码(run -> debug -> swt application)将产生如下所示的一个窗口
2、button的使用
按钮可能的类型有很多,例如:
SWT.BORDER  含有边框的按钮
SWT.CHECK  复选按钮
SWT.PUSH  普通按钮
SWT.RADIO  单选按钮
3、Text的使用
文本框的类型也有很多种选择,例如:
SWT.BORDER 含有边框
SWT.READ_ONLY 只读
下图为包含按钮以及文本框的窗口
设计上述窗口所对应的代码为:
package mypakage;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
public class Myfrm1 {
public Myfrm1() {
super();
}
public static void main(String[] args) {
Display display = new Display( );
        Shell shell = new Shell(display);
        shell.setSize(300, 200);
        shell.setLayout(new RowLayout( ));
        shell.setText("Button Example");
        final Button button = new Button(shell, SWT.BORDER);
        button.setText("Click Me");
        final Text text = new Text(shell, SWT.BORDER);  
        shell.open( );

        while(!shell.isDisposed( )) {
               if(!display.readAndDispatch( )) display.sleep( );
        }
        display.dispose( );
}
}
如果想对控件的位置以及大小进行精确的设置,可以使用setBounds(x, y, width, height)方法来取代shell.setLayout(new RowLayout( ))。例如:button.setBounds(80, 80, 90, 20);
button的监听及事件处理
对按钮单击事件处理的代码:
        button.addSelectionListener(new SelectionListener( )
        {
               public void widgetSelected(SelectionEvent event)
               {
                     text.setText("No worries!");
               }
               public void widgetDefaultSelected(SelectionEvent event)

               {
                     text.setText("No worries!");
               }
        });

将以上代码加入到shell.open之前,当点击按钮时产生以下效果:
分析:由于为button按钮增加了一个监听器,按钮时刻处于被“监控”的状态,当按钮控件被选择(点击)既选择事件发生时,对文本控件进行赋值”No worries”。
根据监听事件的原理,设计如下程序,该程序能够获得鼠标的X坐标,显示在文本框中:
package mypakage;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
public class Myfrm1 {
public Myfrm1() {
super();
}
public static void main(String[] args) {
Display display = new Display( );
        Shell shell = new Shell(display);
        shell.setSize(300, 200);
        shell.setLayout(new RowLayout( ));
        final Text text = new Text(shell, SWT.SHADOW_IN);

        shell.addMouseMoveListener(new MouseMoveListener( )
        {
               public void mouseMove(MouseEvent e)
               {
                     Integer y=new Integer(e.x);  /*将x坐标转换为Integer类型的对象*/
                     text.setText(y.toString());
               }
        });

        shell.open( );
        while(!shell.isDisposed( )) {
               if(!display.readAndDispatch( )) display.sleep( );
        }
        display.dispose( );
}
}
监听方式:
ControlListener 用于处理移动以及尺寸变化

FocusListener 用于处理得到焦点以及失去焦点

KeyListener 处理按键的输入

MouseListener , MouseMoveListener, MouseTrackListener 对鼠标的动作进行处理

SelectionListener 处理控件的选择行为(包括按钮的点击)

注意:监听方式与其所能够处理的事件具有一定的关联性,既监听方式决定了所能够处理事件的种类,例如:

        shell.addMouseListener(new MouseListener( )
        {
            public void mouseMove(MouseEvent e)
           {text.setText("mousemove");}
               public void mouseDoubleClick(MouseEvent e)
               {text.setText("mousedbclc");}
               public void mouseDown(MouseEvent e)
               {}
               public void mouseUp(MouseEvent e)
               {}
        });

你会发现在鼠标移动时,text.setText("mousemove");始终不能够执行;并且mouseDown、mouseUp事件不能够省略,原因就在于MouseListener只能处理mouseDoubleClick、mouseDown、mouseUp三类事件,而且这三类事件不能够分离。
3、List控件
List控件的样式包括:
SWT.BORDER 含有边框

SWT.H_SCROLL 含有水平滚动条

SWT.V_SCROLL 含有垂直滚动条

SWT.SINGLE 允许单选

SWT.MULTI 允许复选

若要创建一个含有从11个元素的List,可以通过以下代码来实现
final List list = new List (shell, SWT.SINGLE);
for (int i=0;i<=10;i++)
   list.add("item"+i);

 

以下实例能够判断List控件中所选择的选项,并且输出显示在控制台中:
package mypakage;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
public class Myfrm1 {
public Myfrm1() {
super();
}
public static void main(String[] args) {
        Display display = new Display ( );
        Shell shell = new Shell (display);
        shell.setText("List Example");
        shell.setSize(300, 200);
        shell.setLayout(new FillLayout(SWT.VERTICAL));
        final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);          
        for (int loopIndex = 0; loopIndex < 100; loopIndex++){
            list.add("Item " + loopIndex);
           }
        list.addSelectionListener(new SelectionListener( )
        {
           public void widgetSelected(SelectionEvent event)
           {
                int  selections[] = list.getSelectionIndices ( );
                String outText = "";
                for (int loopIndex = 0; loopIndex < selections.length;
                    loopIndex++) outText += selections[loopIndex] + " ";
                System.out.println ("You selected: " + outText);
              }
           public void widgetDefaultSelected(SelectionEvent event)
           {
                int [] selections = list.getSelectionIndices ( );
                String outText = "";
                for (int loopIndex = 0; loopIndex < selections.length; loopIndex++)
                    outText += selections[loopIndex] + " ";
               System.out.println ("You selected: " + outText);
             }
          });
          shell.open ( );
          while (!shell.isDisposed ( )) {
              if (!display.readAndDispatch ( )) display.sleep ( );
          }
          display.dispose ( );
}
}

效果图:
 

You selected: 4 5 6 7 8 9 10
分析:list.getSelectionIndices ( )方法将会获得被选择项目的集合, selections[]或者[] elections表示动态一维数组。

4、Menu控件
建立菜单的一般步骤为:
1、在建立菜单时,首先需要建立一个菜单栏,需要使用SWT.BAR属性
Menu menuBar = new Menu(shell, SWT.BAR);

2、在菜单栏的基础之上,创建下拉菜单的所对应的顶级菜单项,需要使用SWT.CASCADE属性
fileMenuHeader = new MenuItem(menuBar, SWT.CASCADE);
fileMenuHeader.setText("&File");

3、建立与顶级菜单项相关的下拉式菜单
dropMenu1 = new Menu(shell, SWT.DROP_DOWN);

4、将顶级菜单项与下拉菜单关联
MenuHeader1.setMenu(dropMenu1);

5、为下拉菜单添加子菜单项
dropitem1= new MenuItem(dropMenu1, SWT.PUSH);
dropitem1.setText("open");

6、最后,在窗口中指定需要显示的菜单栏
shell.setMenuBar(menuBar);

 

菜单的监听及事件
参照按钮的监听以及事件,设计如下程序,当点击 File子菜单下的“open”时,在文本框中显示“click open menu!”
dropitem1.addSelectionListener(new SelectionListener()
   {
      public void widgetSelected(SelectionEvent event)
      {
      text.setText("click open menu!");
      }
      public void widgetDefaultSelected(SelectionEvent event)
      {
      text.setText("click open menu!");
      }
   });
 

5、使用工具栏toobar
建立工具栏可以通过如下方式:ToolBar toolbar = new ToolBar(shell, SWT.NONE);
在工具栏的基础之上创建工具栏子按钮,并且设置子按钮的标题:

ToolItem item1 = new ToolItem(toolbar, SWT.PUSH);
item1.setText("item1");

例如:
        ToolBar toolbar = new ToolBar(shell, SWT.NONE);
        ToolItem item1 = new ToolItem(toolbar, SWT.PUSH);
        item1.setText("item1");
        ToolItem item2 = new ToolItem(toolbar, SWT.PUSH);
        item2.setText("item2");

 

工具栏的监听及事件
实例:创建一个监听对象,将该监听对象应用于每一个按钮,最终来判断鼠标点击的是哪一个按钮,效果图如下。
            Listener listener = new Listener( ) {
                public void handleEvent(Event event) {
                    ToolItem item =(ToolItem)event.widget;
                    String string = item.getText( );
                    text.setText("You selected:" + string);               }
            };
            item1.addListener(SWT.Selection, listener);
            item2.addListener(SWT.Selection, listener);
            item3.addListener(SWT.Selection, listener);
item4.addListener(SWT.Selection, listener);

 

6、滚动条slider的使用
滚动条分为有边框、垂直、水平三种类型,利用slider.setBounds方法可以指定滚动条所在的位置。
滚动条所能够处理事件的包括:
SWT.ARROW_DOWN 向下或向右按钮被点击

SWT.ARROW_UP 向左或向上按钮被点击

SWT.DRAG  滑块按钮被托动

SWT.END 滑块到达终点

SWT.HOME 滑块到达起点

SWT.PAGE_DOWN 下方或右侧的滚动条被点击

SWT.PAGE_UP 上方或左侧的滚动条被点击
实例:根据滑块的位置移动按钮位置
        slider.addListener(SWT.Selection, new Listener( ) {

          public void handleEvent(Event event) {

            switch(event.detail) {

               case SWT.ARROW_DOWN: button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.ARROW_UP:button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.DRAG:button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.END:button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.HOME:button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.PAGE_DOWN:button.setBounds(slider.getSelection(),0,20,10);

                        break;

               case SWT.PAGE_UP:button.setBounds(slider.getSelection(),0,20,10);

                        break;

                    }
            }

});

 


7、树形控件Tree
树形控件使用的方法为,首先创建一个Tree类型的对象,其次在该对象的基础之上继续扩展节点,以及扩展节点的子节点。
final Tree  tree = new Tree(shell, SWT.BORDER);
可以利用tree.setSize方法来改变树形控件的大小。在创建节点时,需要指明该节点所依赖的父节点的名称,如TreeItem item0 = new TreeItem(tree, 0);,那么item0将成为tree对象中的0级(顶级)节点。
如下程序将在tree对象的基础之上产生9个节点:
        final Tree tree = new Tree(shell, SWT.BORDER);

        tree.setSize(290, 290);

        for(int loopIndex1 = 2000; loopIndex1 <= 2008; loopIndex1++) {

            TreeItem item0 = new TreeItem(tree, 0);

            item0.setText("Year " + loopIndex1);

        }
 
在上述实例的基础上为每一个0级节点的基础上扩展出12个节点:
        for(int loopIndex1 = 2000; loopIndex1 <= 2008; loopIndex1++) {

            TreeItem item0 = new TreeItem(tree, 0);

            item0.setText("Year " + loopIndex1);
           
            for(int loopIndex2 = 1; loopIndex2 <= 12; loopIndex2++) {
           
            TreeItem item1 = new TreeItem(item0, 0);
           
            item1.setText("Month " + loopIndex2);
            }

        }
 

8、对话框dialog
对话框是一个依托于主窗体的子窗体,如图所示。
 
例如:当在主窗体中点击按钮时,弹出一个对话框dialog,当关闭对话框时按钮显示“dialog is disposed”
 
        Display display = new Display( );

        final Shell shell = new Shell(display);

        shell.setSize(300, 200);

        shell.setText("main");
       
        final Button opener = new Button(shell, SWT.PUSH);

        opener.setText("Click Me");
       
        opener.setBounds(20, 20, 50, 25);
       
        final Shell dialog = new Shell(shell, SWT.APPLICATION_MODAL |

            SWT.DIALOG_TRIM);
       
        dialog.setText("dialog");
       
        dialog.setBounds(10,10,50,60);
       
        dialog.addDisposeListener(new DisposeListener(){
       
        public void widgetDisposed(DisposeEvent e){

        opener.setText("dialog is disposed");
       
        }
        });
       
        Listener openerListener = new Listener( ) {

            public void handleEvent(Event event) {

                    dialog.open( );

            }

        };

        opener.addListener(SWT.Selection, openerListener);
            
        shell.open( );
       
        while(!dialog.isDisposed( )) {

            if(!display.readAndDispatch( )) display.sleep( );

        }      

        while (!shell.isDisposed( )) {

            if (!display.readAndDispatch( ))

                display.sleep( );

        }

        display.dispose( );

posted on 2007-01-18 15:18 liaojiyong 阅读(833) 评论(0)  编辑  收藏 所属分类: Java


只有注册用户登录后才能发表评论。


网站导航: