JAVA_SWT 事件的四种写法

一:匿名内部类写法

在一个组件下加入以下语句

      text.addMouseListener(new MouseAdapter(){

           public void mouseDoubleClich(MouseEVent e){

         MessageDialog.openInformation(null,"","helloworld"):

}})

这种方式是在事件内部直接实现处理代码,优点是简单方便,但也存在缺点

①:事件处理代码会分散的出现在各个部分,维护起来不方便;

②:如果代码较长,阅读和维护起来麻烦

③:当工具栏、菜单栏也需要相同的行为时,代码无法重用,导致代码臃肿

二:命名内部类写法:

  text.addMouseListener(new MyMouseDoubleClick());

...//定义MyMouseDoubleClick.java

private static final class MyMouseDoubleClick extends MouseAdapter{

          public void mouseDoubleClick(MouseEvent e){

                   MessageDialog.openInformation(null,"","hello world")

}

}

三:外部类写法:

这种方法与第二种方法类似,只是有内部类变为单个外部类

代码略;

四:实现监听器接口的写法:

将类实现相应的接口,这样类本身就成了一个监听器,使得加入监听器的代码可以更简洁,这种方法适合加入监听器的组件较多,且要求监听器的事件处理代码可以被组件共用,需要注意的是

事件方法和其他方法混合在一起,所以应加一些注释来说明。没用事件处理方法可以用空来实现。如果继承了了相应的事件适配器,则可根据需要写相应的方法,另外需要注意,只有接口才有多继承的特性,所以如果类本身已经是一个子类,则只有通过实现接口的方式来实现而不能继承接口的适配器。

        public class Helloworld extends MouseAdapter implements MouseListener{

         public static void main(String[] args){

  .......

       Text text1=new Text(shell,SWT.Border);

      Text text2=new Text(shell, SWt.Border);

     text1.addMouseListener(this);

     text2.addMouseListener(this);

}

    public void mouseDoubleClick(MouseEvent e){

      MessageDialog.openInformation(null,"","hello world");}}

}

}

猜你喜欢

转载自www.cnblogs.com/guoke289/p/9103154.html