<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    sunfruit[請訪問http://www.fruitres.cn]

    --我相信JAVA能走得更遠 QQ:316228067

    #

    [原創]JAVA編寫的使用手機串口發送短信的程序

        --sunfruit

        用JAVA編寫的使用手機串口發送短信的程序

        功能簡介:
            手機通過串口與電腦連接以后,就可以使用該程序發送短信
            如果是紅外連接那么可以使用紅外模擬串口的軟件進行轉換即可
            紅外模擬串口的軟件下載地址http://heart5.chinap4.com/moto388/connect/ircomm2k/download.html
        歡迎大家提意見,交流

       可以直接運行的程序下載地址,環境配置參考包中的txt
       http://m.tkk7.com/Files/sunfruit/comm.rar

        源代碼下載地址
        http://m.tkk7.com/Files/sunfruit/comm_src.rar

    posted @ 2006-02-19 18:08 sunfruit 閱讀(5572) | 評論 (52)編輯 收藏

    [經驗]JAVA驗證字符串轉換為日期的合法性

        --sunfruit

        在處理日期的格式轉換的時候總結些經驗,和大家分享,如下:

           String  text  ="1996-2-1";
           Date  d  =  null; 
           SimpleDateFormat  df  =  new  SimpleDateFormat("yyyy-MM-dd"); 
           df.setLenient(false);//這個的功能是不把1996-13-3 轉換為1997-1-3
            try
           { 
             d  =  df.parse(text); 
           }
           catch(Exception  e)
           { 
             d=new  Date();
             System.out.println("你輸入的日期不合法,請重新輸入"); 
           } 
           String sdata=df.format(d);
           System.out.println(sdata);
        
          這樣輸入1996-2-31這樣的數據也會驗證出來錯誤的,但是前提是要設置Lenient為false

    posted @ 2006-02-19 18:07 sunfruit 閱讀(2933) | 評論 (4)編輯 收藏

    [原創]java的數據庫基類--提供了靈活連接方式和多種的update語句

        --sunfruit

        用JAVA實現了數據庫基類

        JDK版本
            JDK1.4.x
        功能
            實現了靈活的連接數據庫或數據庫連接池
            提供了update的多種方式
            現在提供的有DriverClass和DriverClassTomcat,分別是直接連接和tomcat連接池連接
            可以繼續寫出DriverClassWeblogic等其他的連接方式方到自己指定的地方,然后修改那個xml的class參數就可以了
            修改連接方式的時候無需修改代碼
       
        歡迎大家提意見,交流

        代碼下載
        http://sunfruit.blogchina.com/inc/database.rar

    posted @ 2006-02-19 18:06 sunfruit 閱讀(218) | 評論 (0)編輯 收藏

    用Java事件處理機制實現錄制回放功能

        --sunfruit

       

    用Java事件處理機制實現錄制回放功能

    目前在一些java應用程序的GUI測試工具,可以提供捕獲用戶操作的能力并在代碼被修改之后能夠自動回放用戶的操作。文章將分析Java的事件 處理模型及其原理,介紹了基于事件源識別的捕獲/回放所需要了解的關鍵技術并給出了兩種實現方式。

      1、 Java事件介紹

      1.1什么是事件

      首先我們來回答"什么是事件"這一基本問題。其實事件本身就是一個抽象的概念,他是表現另一對象狀態變化的對象。在面向 對象的程序設計中,事件消息是對象間通信的基本方式。在圖形用戶界面程序中,GUI組件對象根據用戶的交互產生各種類型的事件消息,這些 事件消息由應用程序的事件處理代碼捕獲,在進行相應的處理后驅動消息響應對象做出反應。我們在GUI上進行叫化操作的時候,在點擊某個可 響應的對象時如,按鈕,菜單,我們都會期待某個事件的發生。其實圍繞GUI的所有活動都會發生事件,但Java事件處理機制卻可以讓您挑選出 您需要處理的事件。事件在Java中和其他對象基本是一樣的,但有一點不同的是,事件是由系統自動生成自動傳遞到適當的事件處理程序。

      1.2Java事件處理的演變

      當java的開發者開始解決用java創建應用程序這一問題時,他們就認識到java事件模型的必要性。下面對java事件處理的發展做簡要的概 括。

      在JDK1.0的版本采用用的事件模型,提供了基本的事件處理功能。這是一種包容模型,所有事件都封裝在單一的類Event中,所有事件 對象都由單一的方法handleEvent來處理,這些定義都在Component類中。為此,只有Component類的子類才能充當事件處理程序,事件處理傳遞 到組件層次結構,如果目標組件不能完全處理事件,事件被傳遞到目標組件的容器。

      JDK1.1是編程界的一次革命,修正了前面版本的一些缺陷,同時增加了一些重要的新功能如,RMI、JNI、JDBC、JavaBean。在事件模型 上基本框架完全重寫,并從Java1.0模型遷移到委托事件模型,在委托模型中事件源生成事件,然后事件處理委托給另一段代碼。

      從JDK1.2開始,引入了Swing包事件處理模型功能更強大,更加可定制GUI組件與他們相關聯的支持類。在后面的版本基本保持了整個事 件模型,但加入了一些附加事件類和接口。在1.3版本開始引入Rebot類,它能模擬鼠標和鍵盤事件,并用于自動化測試、自動運行演示、以及 其他要求鼠標和鍵盤控制的應用程序。

      我們把JDK1.0事件處理模型成為java 1.0事件模型,而從jdk1.1后的版本事件處理模型稱為Java 2事件處理模型。

      2、 Java 2事件處理模型

      在Java1.0事件處理模型中事件處理是以如下方法執行的。deliverEvent()用于決定事件的目標,目標是處理事件的組件或容器,此過程 開始于GUI層的最外部而向內運作。當按一個button時,如果檢測到是該按鈕激發的事件,該按鈕會訪問它的deliverEvent()方法,這一操作由 系統完成。一旦識別目標組件,正確事件類型發往組件的postEvent()方法,該方法依次把事件送到handleEvent()方法并且等待方法的返回值 。"true"表明事件完全處理,"false"將使postEvent()方法聯系目標容器,希望完成事件處理。

      下面給一個實例:

     
      import java.applet.*; 
      import java.awt.*; 
       
      public class Button1Applet extends Applet{ 
         public void init(){ 
       add(new Button("Red")); 
       add(new Button("Blue")); 
    } 
    public boolean action(Enent evt,Object whatAction){ 
        if( !( evt.target  instanceof  Button))return false; 
     String buttonlabel=(String)whatAction; 
     if(buttonlabel=="Red")setBackground(Color.red); 
     if(buttonlabel==" Blue")setBackground(Color.blue); 
     repaint(); 
    return true; 
    } 
    
    } 
    

      在Java2處理事件時,沒有采用dispatchEvent()-postEvent()-handleEvent()方式,采用了監聽器類,每個事件類都有相關聯的監聽器 接口。事件從事件源到監聽者的傳遞是通過對目標監聽者對象的Java方法調用進行的。

      對每個明確的事件的發生,都相應地定義一個明確的Java方法。這些方法都集中定義在事件監聽者(EventListener)接口中,這個接 口要繼承java.util.EventListener。 實現了事件監聽者接口中一些或全部方法的類就是事件監聽者。 伴隨著事件的發生,相應的狀態通常都封裝在事件狀態對象中,該對象必須繼承自java.util.EventObject。事件狀態對象作為單參傳遞給應響 應該事件的監聽者方法中。 發出某種特定事件的事件源的標識是:遵從規定的設計格式為事件監聽者定義注冊方法,并接受對指定事件監聽者接口實例的引用。 有時,事件監聽者不能直接實現事件監聽者接口,或者還有其它的額外動作時,就要在一個源與其它一個或多個監聽者之間插入一個事件適配 器類的實例,來建立它們之間的聯系。

      我們來看下面一個簡單的實例:

     
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 
    
    public class SimpleExample extends JFrame { 
      JButton jButton1 = new JButton(); 
    
      public SimpleExample() { 
        try { 
          jbInit(); 
        } 
        catch(Exception e) { 
          e.printStackTrace(); 
        } 
      } 
      public static void main(String[] args) { 
        SimpleExample simpleExample = new SimpleExample(); 
      } 
      private void jbInit() throws Exception { 
        jButton1.setText("jButton1"); 
        jButton1.addActionListener(new SimpleExample_jButton1_actionAdapter(this)); 
        jButton1.addActionListener(new SimpleExample_jButton1_actionAdapter(this)); 
        this.getContentPane().add(jButton1, BorderLayout.CENTER); 
      this.setVisible(true);  
      } 
    
      void jButton1_actionPerformed(ActionEvent e) { 
        System.exit(0); 
      } 
    } 
    
    class SimpleExample_jButton1_actionAdapter implements java.awt.event.ActionListener { 
      SimpleExample adaptee; 
    
      SimpleExample_jButton1_actionAdapter(SimpleExample adaptee) { 
        this.adaptee = adaptee; 
      } 
      public void actionPerformed(ActionEvent e) { 
        adaptee.jButton1_actionPerformed(e); 
      } 
    } 
    
     

    3、 事件捕獲與回放

     

      3.1 Java事件生命周期

      Java事件和萬事一樣有其生命周期,會出生也會消亡。下圖3.1給出了Java事件生命周期的示意圖,

      事件最初由事件源產生,事件源可以是GUI組件Java Bean或由生成事件能力的對象,在GUI組件情況下,事件源或者是組件的同位體( 對于Abstract Window Toolkit[awt]GUI組件來說)或組件本身(對于Swing組件來說)。事件生成后放在系統事件隊列內部。現在事件處于事件分發線程的控 制下。事件在隊列中等待處理,然后事件從事件隊列中選出,送到dispatchEvent()方法,dispatchEvent()方法調用processEvent()方法并將 事件的一個引用傳遞給processEvent()方法。此刻,系統會查看是否有送出事件的位置,如果沒有這種事件類型相應的已經注冊的監聽器,或 者如果沒有任何組件受到激活來接收事件類型,事件就被拋棄。當然上圖顯示的是AWTEvent類的子類的生命周期。dispatchEvent()方法和proc essEvent()方法把AWTEvent作為一個參數。但對,javax.swing.event并不是AWTEvent子類,而是從EventObject直接繼承過來,生成這些事件 的對象也會定義fireEvent()方法,此方法將事件送到包含在對象監聽器列表內的那種類型的任何監聽器。

      3.2 Java事件捕獲

      從上面的分析我們知道,任何事件產生到dispatchEvent()方法分發方法前,所有的事件都是存放在系統事件的隊列中,而且所有的事件都 由dispatchEvent()方法來分派。所以只要能重載dispatchEvent()方法就可以獲取系統的所有事件,包括用戶輸入事件。一般來說,系統事件 隊列的操作對用戶來說是可以控制。它在后臺自動完成所要完成的事情,使用EventQueue類可以查看甚至操縱系統事件隊列。

      Java提供了EventQueue類來訪問甚至操縱系統事件隊列。EventQueue類中封裝了對系統事件隊列的各種操作,除dispatchEvent()方法 外,其中最關鍵的是提供了push()方法,允許用特定的EventQueue來代替當前的EventQueue。只要從EventQueue類中派生一個新類,然后通過p ush()方法用派生類來代替當前的EventQueue類即可。這樣,所有的系統事件都會轉發到派生EventQueue類。然后,再在派生類中重載dispatch Event()方法就可以截獲所有的系統事件,包括用戶輸入事件。下面一段代碼給出一個操縱EventQueue的實例:

     
    import java.awt.*; 
    import java.awt.event.*; 
    
    public class GenerateEventQueue extends Frame implements ActionListener{ 
      Button button1 = new Button(); 
      TextField textField1 = new TextField(); 
    
      public GenerateEventQueue() { 
        try { 
          jbInit(); 
        } 
        catch(Exception e) { 
          e.printStackTrace(); 
        } 
      } 
      public static void main(String[] args) { 
        GenerateEventQueue generateEventQueue = new GenerateEventQueue(); 
      } 
      private void jbInit() throws Exception { 
        button1.setLabel("button1"); 
        button1.addActionListener(this) ; 
        textField1.setText("textField1"); 
    
        this.add(button1, BorderLayout.SOUTH); 
        this.add(textField1, BorderLayout.CENTER); 
        EventQueue eq=getToolkit().getSystemEventQueue() ; 
        eq.postEvent(new ActionEvent(button1,ActionEvent.ACTION_PERFORMED,"test" )) ; 
        addWindowListener(new WinListener()); 
        setBounds(100,100,300,200); 
        setVisible(true); 
      } 
    
      public void actionPerformed(ActionEvent e) { 
        textField1.setText("event is :"+e.getActionCommand()) ; 
      } 
    
    } 
    
    class WinListener extends WindowAdapter{ 
      public void windowClosing(WindowEvent we){ 
        System.exit(0) ; 
      } 
    } 
    

      運行結果如下圖所示:

      在文本域中首先出現的是"event is :test",這是因為首先得到處理的是EventQueue對象發送到系統事件隊列上的ActionEvent。

      下面的代碼簡單說明了如何捕獲事件:

     
      import java.awt.EventQueue; 
    import java.awt.*; 
    import java.util.*; 
    public class MyQueueEvent extends EventQueue {//定義EventQueue的子類 
      public MyQueueEvent() { 
      } 
      public static void main(String[] args) { 
        SimpleExample.main(new String[]{null}) ; 
        MyQueueEvent myQueueEvent1 = new MyQueueEvent(); 
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(myQueueEvent1) ; 
      } 
    //在這里重載事件分發的方法 
      public void dispatchEvent(AWTEvent ae){ 
         
        if(ae.getSource() instanceof javax.swing.JButton) 
        System.out.println("My apture:"+((javax.swing.JButton)ae.getSource()).getText()) ; 
        super.dispatchEvent(ae); 
      } 
      

      這個程序可以打印出當前應用的所有的事件,可以將這些事件中選出你需要的事件保存當然你還需要解析該控件的特征。在上面加黑部 分的代碼,打印事件源控件的名稱。

      除此之外,還可以通過實現java.awt.event. AWTEventListener接口實現對事件的捕獲。這個偵聽器接口可以接收Component or MenuComponent 以及它們的派生類在整個系統范圍內所分發的事件,AWTEventListeners只是被動的監控這些事件。如果要監控系統事件,除了要實現接口,還 要用Toolkit的addAWTEventListener方法注冊這個偵聽器。

      下面我們來看一個實例:

     
    import java.awt.AWTEvent; 
    import java.awt.Frame; 
    import java.awt.Toolkit; 
    import java.awt.Window; 
    import java.awt.event.AWTEventListener; 
    import java.awt.event.WindowEvent; 
    
    import java.util.ArrayList; 
    import java.lang.ref.WeakReference; 
    public class MyAWTEventListener implements AWTEventListener{ 
      private  static MyAWTEventListener s_singleton = null;//保證該類只被初始化一次 
      public static MyAWTEventListener getInstance(){ 
        if(s_singleton==null){ 
         s_singleton=new MyAWTEventListener(); 
        } 
        return s_singleton; 
      } 
      private MyAWTEventListener(){ 
        //注意下面這行代碼,如果沒有這行代碼,將無法接收到系統分發的事件 
        // 下面代碼在注冊時,只請求了接收WINDOW_EVENT_MASK事件 
       //但實際上,你可以接收其他AWTEvent中定義的事件類型 
    Toolkit.getDefaultToolkit().addAWTEventListener(this, 
            AWTEvent.COMPONENT_EVENT_MASK 
    ); 
      } 
      /* 
         這就是接口方法的實現 
    */ 
    public void eventDispatched(final AWTEvent theEvent) { 
            processEvent(theEvent); 
      } 
      private static void processEvent(final AWTEvent theEvent) { 
            System.out.println(theEvent.getSource() ) ;//打印事件源 
        switch (theEvent.getID()) { 
            case WindowEvent.WINDOW_OPENED: 
              //System.out.println(((Frame)theEvent.getSource()).getTitle() ) ; 
            case WindowEvent.WINDOW_ACTIVATED: 
            case WindowEvent.WINDOW_DEACTIVATED: 
            case WindowEvent.WINDOW_CLOSING: 
            default: break; 
            } 
        } 
    } 
    
    3.3 Java事件回放

      事件的回放其實比較簡單了,比如我們現在記錄的是frame1下的jButton1點擊事件回放。看下面一段簡單的程序,只要點一下jButton1, 就在控制臺打印一次"click me"的字符串。

     
    import java.awt.*; 
    import javax.swing.*; 
    import java.awt.event.*; 
    
    public class Frame1 extends JFrame { 
      private JButton jButton1 = new JButton(); 
    
      public Frame1() { 
        try { 
          jbInit(); 
        } 
        catch(Exception e) { 
          e.printStackTrace(); 
        } 
      } 
      public static void main(String[] args) { 
        Frame1 frame1 = new Frame1(); 
    frame1.setVisible(true) ; 
    
      } 
      private void jbInit() throws Exception { 
        jButton1.setText("jButton1"); 
        jButton1.addActionListener(new java.awt.event.ActionListener() { 
          public void actionPerformed(ActionEvent e) { 
            jButton1_actionPerformed(e); 
          } 
        }); 
        this.setTitle("Test"); 
        this.getContentPane().add(jButton1, BorderLayout.CENTER); 
      } 
    
      void jButton1_actionPerformed(ActionEvent e) { 
        System.out.println("click me") ; 
      } 
    } 
    

      下面是回放的程序,在下面的程序中用到了java.awt.Robot類,這個類通常用來在自動化測試或程序演示中模擬系統事件,在某些需要 控制鼠標或鍵盤的應用程序中這個類也是很有用,這個類主要的目的就是為方便的實現java的GUI自動化測試平臺。在事件回放時,我們同樣需 要該類來模擬生成系統的事件,完成記錄的操作的回放,在下面的代碼中,給出了一個簡單的例子。

     
    import java.awt.*; 
    import javax.swing.*; 
    import java.awt.event.*; 
    public class TestReplay extends Thread{ 
      public static void main(String[] args) { 
        try{ 
          //啟動要回放的應用程序 
          Frame1.main(new String[]{null}) ; 
       //等應用程序啟動后延遲3秒再進行回放 
          Thread.currentThread().sleep(3000) ; 
          Robot robottest=new Robot(); 
          robottest.waitForIdle(); 
          //根據標題名獲取當前應用的主窗體,在本例中為"test" 
          Frame jframe=getFrame("test");; 
         //根據給定的窗體和窗體中要find的控件的名稱來獲取控件的引用    
    JButton jbtn=getButton(jframe,"jButton1"); 
    //將鼠標移到控件所在的位置 
          robottest.mouseMove(jbtn.getLocationOnScreen().x+jbtn.getWidth()/2 
       ,jbtn.getLocationOnScreen().y+jbtn.getHeight()/2) ; 
      //在控件所在位置,生成鼠標點擊事件 
          robottest.mousePress(InputEvent.BUTTON1_MASK ) ; 
          robottest.mouseRelease(InputEvent.BUTTON1_MASK ) ; 
        }catch(Exception ee){ 
          ee.printStackTrace() ; 
        } 
      } 
      //獲得標題為title的frame 
      private static Frame getFrame(String title){ 
        Frame[] jframes=(Frame[])JFrame.getFrames(); 
        for(int i=0;i<jframes.length ;i++){ 
          if(jframes[i].getTitle().equalsIgnoreCase(title))return jframes[i]; 
        } 
        return null; 
    
      } 
      //獲取某一個frame下的某個名為jButton1的控件 
      private static JButton getButton(Frame jf,String text){ 
    /*注意下面這行代碼,因為實例比較簡單只有ContentPane一個Container類型的控件, 
    如果在JFrame中有多個Container控件//的話,必須進行遞歸處理,搜索出所有的控件 
    */ 
        Component[] coms=((JFrame)jf).getContentPane().getComponents(); 
        for(int i=0;i<coms.length ;i++){ 
          if(!(coms[i] instanceof JButton))continue; 
          if(((JButton)coms[i]).getText().equalsIgnoreCase(text))return (JButton)coms[i]; 
        } 
        return null; 
      } 
      public void run(){ 
    
      } 
    } 
    

      該程序運行完,你會發現在控制臺同樣打印出了:

      "click me"的字符串說明事件被正確回放了。

      當然還可以通過直接操縱系統事件隊列實現輸入事件的回放。先通過記錄下的窗口/組件名獲得對應窗口引用,然后重構鼠標/鍵盤事件 ,最后將重構的事件直接放入系統事件隊列,由分派線程執行后續的事件分派工作。還需要解決關鍵問題如何能根據窗口名稱獲得其引用。這 里還是可以通過系統事件隊列來實現的,因為Java程序在新建/刪除一個容器時都會向系統事件隊列發出一個Containerevent事件,其中包含了 對該容器的引用。所以,事件回放器在載入被測測試程序后便監視系統隊列,截獲所有的Containerevent事件。如果新建容器,便獲得新建Con tainer的引用。因為所有的Container都實現了getComponets(),可以返回所有該容器所包含的組件或容器,只需要保存到一個HashMap結構中 ,需要時檢索出來就可以了。該過程所用到的知識,其實在上面都有提到而且在實際引用中,既然Robot已經幫我們完成許多事情,也沒有必要 自己再去重構一個鼠標或鍵盤事件了,不過有興趣的朋友也可以去試試。

      4、 結束語

      隨著我國軟件業的發展,軟件測試技術作為軟件質量保證的重要環節越來越受到重視,而在基于GUI的應用中采用自動化測試工具可以提高 軟件測試的有效性和效率,特別在回歸測試中可以大大減少人力投入,還可以提高測試腳本的復用。因此,軟件自動測試平臺開發已經成為軟 件測試的一個重要領域。本文介紹了基于Java的GUI應用的自動測試平臺開發需要的基本但關鍵的捕獲、回放功能,所有相關系統開發其實都離 不開本文說的方法。

    posted @ 2006-02-19 18:06 sunfruit 閱讀(323) | 評論 (0)編輯 收藏

    [原創]JAVA數據加密解密的實例

        --sunfruit

        關于加密解密的理論知識已經不少了,這里只給出一個加密解密以及生成key的源代碼,給大家參考

        源代碼下載地址:
            http://sunfruit.blogchina.com/inc/des.rar

    posted @ 2006-02-19 18:05 sunfruit 閱讀(2564) | 評論 (4)編輯 收藏

    [原創]JAVA讀取文件或是數據流的源代碼--涵蓋了多種形式

        --sunfruit

        java讀取文件或是文件流的代碼,涵蓋了讀取jar文件中的文件流,網絡文件流等,有些讀取方式為了防止編碼轉換帶來的問題,采取了動態byte[]的方式讀取,源碼如下

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.BufferedOutputStream;
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;

    public class Util {

      public Util() {
      }
      /**
       * 讀取源文件內容
       * @param filename String 文件路徑
       * @throws IOException
       * @return byte[] 文件內容
       */
      public static byte[] readFile(String filename) throws IOException {

        File file =new File(filename);
        if(filename==null || filename.equals(""))
        {
          throw new NullPointerException("無效的文件路徑");
        }
        long len = file.length();
        byte[] bytes = new byte[(int)len];

        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
        int r = bufferedInputStream.read( bytes );
        if (r != len)
          throw new IOException("讀取文件不正確");
        bufferedInputStream.close();

        return bytes;

      }

      /**
       * 將數據寫入文件
       * @param data byte[]
       * @throws IOException
       */
      public static void writeFile(byte[] data,String filename) throws IOException {
        File file =new File(filename);
        file.getParentFile().mkdirs();
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(data);
        bufferedOutputStream.close();

      }

      /**
       * 從jar文件里讀取class
       * @param filename String
       * @throws IOException
       * @return byte[]
       */
      public byte[] readFileJar(String filename) throws IOException {
        BufferedInputStream bufferedInputStream=new BufferedInputStream(getClass().getResource(filename).openStream());
        int len=bufferedInputStream.available();
        byte[] bytes=new byte[len];
        int r=bufferedInputStream.read(bytes);
        if(len!=r)
        {
          bytes=null;
          throw new IOException("讀取文件不正確");
        }
        bufferedInputStream.close();
        return bytes;
      }
     
      /**
       * 讀取網絡流,為了防止中文的問題,在讀取過程中沒有進行編碼轉換,而且采取了動態的byte[]的方式獲得所有的byte返回
       * @param bufferedInputStream BufferedInputStream
       * @throws IOException
       * @return byte[]
       */
      public byte[] readUrlStream(BufferedInputStream bufferedInputStream) throws IOException {
        byte[] bytes = new byte[100];
        byte[] bytecount=null;
        int n=0;
        int ilength=0;
        while((n=bufferedInputStream.read(bytes))>=0)
        {
          if(bytecount!=null)
            ilength=bytecount.length;
          byte[] tempbyte=new byte[ilength+n];
          if(bytecount!=null)
          {
            System.arraycopy(bytecount,0,tempbyte,0,ilength);
          }

          System.arraycopy(bytes,0,tempbyte,ilength,n);
          bytecount=tempbyte;

          if(n<bytes.length)
            break;
        }
        return bytecount;
      }

    }

    posted @ 2006-02-19 18:04 sunfruit 閱讀(6071) | 評論 (1)編輯 收藏

    [原創]用JAVAMAIL發送郵件的一個簡單例子

        --sunfruit

        寫了一個收發郵件的應用程序[在列表里面可以看到]但是畢竟有些復雜,關鍵部分其實也就是幾行代碼,為了大家使用方便,我把發送郵件的代碼單獨拿了出來,并且分為發送附件/不發送附件兩個方法,便于大家查看,只是什么設計啦,編程思想啦,等等就談不到了,呵呵,大家將就吧

        JDK版本
            1.4.x
        其   他
            JAVAMAIL相關包
        功能簡介:
            簡單的郵件發送功能,可以發送附件

        源代碼如下

    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    import java.util.*;
    import java.util.*;
    import java.text.*;
    import java.io.*;
    public class SendMail
    {
        //傳入的參數有密碼、姓名、誰發、發給誰、主題、正文內容、smtp地址、附件文件路徑、附件的新文件名、發送類型(text/html)
        //發送郵件主函數
        public String sendmail(int myport,String password,String username,String myfrom,String myto,String mysubject,String mytext,String mysmtp,String[] filepath,String[] newfilename,String htmlandtext)
        {
                try{
                    int indexstr=0;
                    if (filepath[0]!=null && !filepath[0].equals(""))
                        indexstr=1;
                        //替換字符串
                   //     jbemail myjbemail=new jbemail();
                   //     filepath=myjbemail.myreplace(filepath,"\\","\\\\");
                   //     System.out.println("附件地址"+filepath+"服務器地址"+mysmtp+mysmtp.length());
                        //Properties props = new Properties();
                    Properties props = System.getProperties();
                    Session sendMailSession;
                    Store store;  //收郵件時使用
                    Transport transport;//發郵件時使用
                    props.put("mail.smtp.host",mysmtp);
                    props.put("mail.smtp.auth","true");
                    SmtpAuthenticator sa=new SmtpAuthenticator(username,password);
                    sendMailSession = Session.getInstance(props,sa);
                    //sendMailSession = Session.getInstance(props,null);
                    sendMailSession.setDebug(true);

                    MimeMessage newMessage = new MimeMessage(sendMailSession);
                    newMessage.setFrom(new InternetAddress(myfrom));
                    newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(myto));
                    //設定郵件格式
                    newMessage.setSentDate(new Date());
                    System.out.println(htmlandtext+"郵件正文格式");
                    Multipart multipart = new MimeMultipart();
                    if (htmlandtext.equals("text"))
                    {
                        //獲得文本格式的郵件

                        newMessage.setSubject(mysubject);
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setText(mytext);
                        multipart.addBodyPart(messageBodyPart);
                    }
                    else if(htmlandtext.equals("html"))
                    {
                        //設置郵件內容,將郵件body部分轉化為HTML格式
                        newMessage.setSubject(mysubject,"gb2312");
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setDataHandler(new DataHandler(mytext,"text/html;charset=gb2312"));
                        multipart.addBodyPart(messageBodyPart);
                    }
                    if (indexstr>0)
                    {

                        for(int i=0;i                    {
                            if (newfilename[i]!=null)
                            {
                                //創建BodyPart對象以便獲得附件
                                BodyPart messageBodyPart = new MimeBodyPart();
                                System.out.println("附件地址"+filepath[i]);
                                DataSource source = new FileDataSource(filepath[i]);
                                messageBodyPart.setDataHandler(new DataHandler(source));
                                messageBodyPart.setFileName(newfilename[i]);
                                multipart.addBodyPart(messageBodyPart);
                            }
                        }
                    }
                    //將正文和附件添加到郵件中
                    newMessage.setContent(multipart);
                    newMessage.saveChanges();
                    //transport = sendMailSession.getStore("pop3");
                    transport = sendMailSession.getTransport("smtp");
                    transport.connect(mysmtp,myport,username,password);
                    //transport.connect();
                    transport.send(newMessage,newMessage.getAllRecipients());
                    System.out.println("成功發送到"+myto);
                    return "ok";
            }
            catch(MessagingException m)
            {
                    System.out.println(m.toString()+"失敗");
                    return myto;
            }
        }
        //不含發送附件的函數
        //傳入的參數有port地址、密碼、姓名、誰發、發給誰、主題、正文內容、smtp地址、發送類型(text/html)
        public String sendmail(String mailPathlog,int myport,String password,String username,String myfrom,String myto,String mysubject,String mytext,String mysmtp,String htmlandtext)
        {
                try{
                    //解碼
                    mysubject=java.net.URLDecoder.decode(mysubject);
                        //Properties props = new Properties();
                    Properties props = System.getProperties();
                    Session sendMailSession;
                    Store store;  //收郵件時使用
                    Transport transport;//發郵件時使用
                    props.put("mail.smtp.host",mysmtp);
                    props.put("mail.smtp.auth","true");
                    SmtpAuthenticator sa=new SmtpAuthenticator(username,password);
                    //身份驗證
                    sendMailSession = Session.getInstance(props,sa);
                    //sendMailSession = Session.getInstance(props,null);
                    sendMailSession.setDebug(true);
                    MimeMessage newMessage = new MimeMessage(sendMailSession);
                    try
                    {
                      newMessage.setFrom(new InternetAddress(myfrom,"法律之星"));
                      newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(myto));
                    }
                    catch(java.io.UnsupportedEncodingException ex)
                    {
                       System.out.println(ex.toString());
                    }
                    //設定郵件格式
                    newMessage.setSentDate(new Date());
                    System.out.println(htmlandtext+"郵件正文格式");
                    Multipart multipart = new MimeMultipart();
                    if (htmlandtext.equals("text"))
                    {
                        //獲得文本格式的郵件

                        newMessage.setSubject(mysubject);
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setText(mytext);
                        multipart.addBodyPart(messageBodyPart);
                    }
                    else if(htmlandtext.equals("html"))
                    {
                        //設置郵件內容,將郵件body部分轉化為HTML格式
                        newMessage.setSubject(mysubject,"gb2312");
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setDataHandler(new DataHandler(mytext,"text/html;charset=gb2312"));
                        multipart.addBodyPart(messageBodyPart);
                    }
                    //將正文添加到郵件中
                    newMessage.setContent(multipart);
                    newMessage.saveChanges();
                    //transport = sendMailSession.getStore("pop3");
                    transport = sendMailSession.getTransport("smtp");
                    transport.connect(mysmtp,myport,username,password);
                    //transport.connect();
                    transport.send(newMessage,newMessage.getAllRecipients());
                    System.out.println("成功發送到"+myto+mytext);
                    return "ok";
            }
            catch(MessagingException m)
            {
                    System.out.println(m.toString()+"失敗");
                    //生成當前日期
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    Date dateTime= new Date();
                    String sDateTime=dateFormat.format(dateTime);
                    //生成日志文件
                    try
                    {
                        File filelog=new File(mailPathlog+"\\"+"mainlog.txt");
                        BufferedWriter out2=new BufferedWriter(new FileWriter(filelog.getPath(),true));
                        String newline = System.getProperty("line.separator");
                        out2.write(sDateTime+"/"+mysmtp+"/"+myfrom+"/"+myto+"/"+m.toString()+"/"+newline);
                        out2.close();
                    }
                    catch (IOException ex)
                    {
                        System.out.println(ex.toString());
                    }
                    return myto;
            }
        }
        class SmtpAuthenticator extends Authenticator
        {
            //SMTP身份驗證
            public SmtpAuthenticator(String username,String password)
            {
                this.username=username;
                this.password=password;
            }
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new  PasswordAuthentication(this.username,this.password);
            }
            String username=null;
            String password=null;
        }
    }

    posted @ 2006-02-19 18:03 sunfruit 閱讀(1793) | 評論 (4)編輯 收藏

    [原創]JAVA用戶自定義事件監聽完整例子

        --sunfruit

        很多介紹用戶自定義事件都沒有例子,或是例子不全,下面寫了一個完整的例子,并寫入了注釋以便參考,完整的實例源代碼如下:

    package demo;

    import java.util.EventObject;

    /**
     * Title: 事件處理類,繼承了事件基類
     * Description: 
     * Copyright: Copyright (c) 2005
     * Company: cuijiang
     * @author not attributable
     * @version 1.0
     */
    public class DemoEvent extends EventObject
    {
      private Object obj;
      private String sName;
      public DemoEvent(Object source,String sName)  {
        super(source);
        obj = source;
        this.sName=sName;
      }
      public Object getSource()
      {
        return obj;
      }
      public void say()
      {
        System.out.println("這個是 say 方法...");
      }

      public String getName()
      {
        return sName;
      }
    }

    package demo;

    import java.util.EventListener;

    /**
     * Title: 監聽器接口
     * Description: 
     * Copyright: Copyright (c) 2005
     * Company: cuijiang
     * @author not attributable
     * @version 1.0
     */
    public interface DemoListener extends EventListener{
      public void demoEvent(DemoEvent dm);
    }

    package demo;

    import java.util.*;

    /**
     *Title: 使用事件的類
     * Description: 該類實現了監聽器的添加和監聽器方法的執行,并且實現了由于屬性的改變而執行事件
     * Description: 在添加、刪除、執行監聽器的時候都要注意同步問題
     * Copyright: Copyright (c) 2005
     * Company: cuijiang
     * @author not attributable
     * @version 1.0
     */
    public class DemoSource{
      private Vector repository = new Vector();
      private DemoListener dl;
      private String sName="";

      public DemoSource()
      {
      }

      //注冊監聽器,如果這里沒有使用Vector而是使用ArrayList那么要注意同步問題
      public void addDemoListener(DemoListener dl)
      {
        repository.addElement(dl);//這步要注意同步問題
      }

      //如果這里沒有使用Vector而是使用ArrayList那么要注意同步問題
      public void notifyDemoEvent(DemoEvent event) {
        Enumeration enum = repository.elements();//這步要注意同步問題
        while(enum.hasMoreElements())
        {
          dl = (DemoListener)enum.nextElement();
          dl.demoEvent(event);
        }
      }

      //刪除監聽器,如果這里沒有使用Vector而是使用ArrayList那么要注意同步問題
      public void removeDemoListener(DemoListener dl)
      {
        repository.remove(dl);//這步要注意同步問題
      }

      /**
       * 設置屬性
       * @param str1 String
       */
      public void setName(String str1)
      {
        boolean bool=false;
        if(str1==null && sName!=null) bool=true;
        else if(str1!=null && sName==null) bool=true;
        else if(!sName.equals(str1)) bool=true;

        this.sName=str1;

        //如果改變則執行事件
        if(bool) notifyDemoEvent(new DemoEvent(this,sName));
      }

      public String getName()
      {
        return sName;
      }
    }

    package demo;

    import java.lang.Thread;

    /**
     * Title: 測試類
     * Description: 測試了由于改變屬性而引起的事件發生
     * Copyright: Copyright (c) 2005
     * Company: cuijiang
     * @author not attributable
     * @version 1.0
     */
    public class TestDemo
        implements DemoListener {
      private DemoSource ds;

      public TestDemo()
      {
        ds=new DemoSource();
        ds.addDemoListener(this);
        System.out.println("添加監聽器完畢");
        try {
          Thread.sleep(3000);
          //改變屬性,觸發事件
          ds.setName("改變屬性,觸發事件");
        }
        catch (InterruptedException ex) {
          ex.printStackTrace();
        }

        ds.addDemoListener(this);
        System.out.println("添加監聽器完畢2");
        try {
          Thread.sleep(3000);
          //改變屬性,觸發事件
          ds.setName("改變屬性,觸發事件2");
        }
        catch (InterruptedException ex) {
          ex.printStackTrace();
        }

        ds.removeDemoListener(this);
        System.out.println("添加監聽器完畢3");
        try {
          Thread.sleep(3000);
          //改變屬性,觸發事件
          ds.setName("改變屬性,觸發事件3");
        }
        catch (InterruptedException ex) {
          ex.printStackTrace();
        }


      }

      public static void main(String args[])
      {

        new TestDemo();
      }

      /**
       * demoEvent
       * @param dm DemoEvent
       * @todo Implement this test.DemoListener method
       */
      public void demoEvent(DemoEvent dm) {
        System.out.println("事件處理方法");
        System.out.println(dm.getName());
        dm.say();
      }
    }

    posted @ 2006-02-19 17:59 sunfruit 閱讀(856) | 評論 (0)編輯 收藏

    [原創]JAVA編寫的帶有復選框的資源管理器樹目錄

        --sunfruit

        用JAVA實現了帶有復選框的樹目錄


        JDK版本
            JDK1.4.x
        功能
            實現了帶有復選框的資源管理器樹目錄,還有需要改進的地方,我在以后更新,如果那位朋友有好的建議歡迎提出
       
        歡迎大家提意見,交流
       
        代碼如下
       
    import javax.swing.tree.*;
    import javax.swing.filechooser.*;
    import javax.swing.event.*;
    import java.awt.Cursor;
    import java.awt.Component;
    import java.awt.Font;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;

    /**
     * Title: 系統級樹目錄
     * Description: 
     * Copyright: Copyright (c) 2004
     * Company: 
     * @author cuijiang contact cj0063@sina.com or cuij7718@yahoo.com.cn
     * @version 1.0
     */
    public class AgileSuperJTreeBasic
        extends JTree
        implements TreeExpansionListener, TreeSelectionListener, MouseListener {
      protected DefaultTreeModel treeModel;
      protected FileSystemView fileSystemView; //建立文件系統視類對象
      protected FileNode root;

      public AgileSuperJTreeBasic() {
        Font myFont = new Font("宋體", 11, 12);
        fileSystemView = FileSystemView.getFileSystemView();
        root = new FileNode(fileSystemView.getRoots()[0]);
        root.explore();
        treeModel = new DefaultTreeModel(root);
        this.setModel(treeModel); //設定樹形菜單
        this.addTreeExpansionListener(this); //打開/關閉節點事件
        this.addTreeSelectionListener(this); //選擇的事件
        this.setCellRenderer(new MyTreeCellRenderer()); //生成圖標
        this.setFont(myFont);
        this.setRootVisible(true);
        this.setRowHeight(18);
        this.addMouseListener(this);
      }

      //圖標生成類
      protected class MyTreeCellRenderer
          extends JPanel
          implements TreeCellRenderer {
        JCheckBox check = new JCheckBox();
        BorderLayout borderLayout1 = new BorderLayout();
        JLabel label = new JLabel();
        public MyTreeCellRenderer() {
          this.setLayout(null);

          this.add(check);
          this.add(label);
          check.setBackground(UIManager.getColor("Tree.textBackground"));
          label.setBackground(UIManager.getColor("Tree.textBackground"));
          this.setBackground(UIManager.getColor("Tree.textBackground"));

        }

        public Dimension getPreferredSize() {
          Dimension checkDimension = check.getPreferredSize();
          Dimension labelDimension = label.getPreferredSize();
          return new Dimension(checkDimension.width + labelDimension.width,
                               (checkDimension.height < labelDimension.height ?
                                labelDimension.height : checkDimension.height));
        }

        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                      boolean sel, boolean expanded,
                                                      boolean leaf, int row,
                                                      boolean hasFocus) {
          String stringValue = tree.convertValueToText(value, sel, expanded, leaf,
              row, hasFocus);
          setEnabled(tree.isEnabled());
          label.setFont(tree.getFont());
          check.setSelected( ( (FileNode) value).isSelected());
          //設置圖標為系統的文件類型圖標
          FileSystemView fileSystemView = FileSystemView.getFileSystemView();
          label.setIcon(fileSystemView.getSystemIcon( ( (FileNode) value).getFile()));
          label.setText(stringValue);
          return this;
        }

        public void doLayout() {
          Dimension checkDimension = check.getPreferredSize();
          Dimension labelDimension = label.getPreferredSize();
          int checkY = 0;
          int labelY = 0;
          if (checkDimension.height > labelDimension.height) {
            labelY = (checkDimension.height - labelDimension.height) / 2;
          }
          else {
            checkY = (labelDimension.height - checkDimension.height) / 2;
          }
          check.setLocation(0, checkY);
          check.setBounds(0, checkY, checkDimension.width, checkDimension.height);
          label.setLocation(checkDimension.width, labelY);
          label.setBounds(checkDimension.width, labelY, labelDimension.width,
                          labelDimension.height);
        }

      }

      //節點張開事件
      public void treeExpanded(TreeExpansionEvent event) {
        //判斷是否是葉節點
        //if (this.getLastSelectedPathComponent() == null) {
          //System.out.println("ok");
          //return;
        //}
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        TreePath path = event.getPath();
        //System.out.println(path.toString());
        FileNode node = (FileNode) path.getLastPathComponent();
        node.explore();
        treeModel.nodeStructureChanged(node);
        this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

      }

      //節點閉合事件
      public void treeCollapsed(TreeExpansionEvent event) {

      }

      //文件節點類
      protected class FileNode
          extends DefaultMutableTreeNode {

        private boolean isSelected = false;
        private boolean explored = false;

        public FileNode(File file) {
          this(file, false);
        }

        public FileNode(File file, boolean bool) {
          super(file);
          this.isSelected = bool;
        }

        //
        public boolean isSelected() {
          return isSelected;
        }

        public void setSelected(boolean isSelected) {
          this.isSelected = isSelected;
          if (children != null) {
            Enumeration enum = children.elements();
            while (enum.hasMoreElements()) {
              FileNode node = (FileNode) enum.nextElement();
              node.setSelected(isSelected);
            }
          }
        }

        //
        public boolean getAllowsChildren() {
          return isDirectory();
        }

        public boolean isLeaf() {
          return!isDirectory();
        }

        public File getFile() {
          return (File) getUserObject();
        }

        public boolean isExplored() {
          return explored;
        }

        public void setExplored(boolean b) {
          explored = b;
        }

        public boolean isDirectory() {
          return getFile().isDirectory();
        }

        public String toString() {
          File file = (File) getUserObject();
          String filename = file.toString();
          int index = filename.lastIndexOf(File.separator);
          return (index != -1 && index != filename.length() - 1)
              ? filename.substring(index + 1) : filename;
        }

        public void explore() {
          if (!isExplored()) {
            File file = getFile();
            File[] children = file.listFiles();
            if (children == null || children.length == 0)
              return;
            for (int i = 0; i < children.length; ++i) {
              File f = children[i];
              if (f.isDirectory())
                add(new FileNode(children[i], isSelected));
            }
            explored = true;
          }
        }

      }

      /**
       * 選擇節點觸發的事件
       * 繼承或是直接引用需要重新寫此方法
       * @param e
       */
      public void valueChanged(TreeSelectionEvent e) {
        //文件路徑
        String sFilePath = "";
        Object myobj = this.getLastSelectedPathComponent();
        if (myobj != null) {
          sFilePath = ( (File) ( ( (DefaultMutableTreeNode) (myobj)).getUserObject())).
              getPath();
        }
        //System.out.println(sFilePath);
      }

      /**
       * Invoked when the mouse button has been clicked (pressed and released) on a
       * component.
       * @param e MouseEvent
       * @todo Implement this java.awt.event.MouseListener method
       */
      public void mouseClicked(MouseEvent e) {
        int count = e.getClickCount();

        if (count != 1) {
          //System.out.println(count);

        }
        else {
          int x = e.getX();
          int y = e.getY();
          int row = this.getRowForLocation(x, y);
          TreePath path = this.getPathForRow(row);
          if (path != null) {
            FileNode node = (FileNode) path.getLastPathComponent();
            boolean isSelected = ! (node.isSelected());
            node.setSelected(isSelected);
            ( (DefaultTreeModel)this.getModel()).nodeChanged(node);
          }
        }

      }

      /**
       * Invoked when a mouse button has been pressed on a component.
       * @param e MouseEvent
       * @todo Implement this java.awt.event.MouseListener method
       */
      public void mousePressed(MouseEvent e) {
      }

      /**
       * Invoked when a mouse button has been released on a component.
       * @param e MouseEvent
       * @todo Implement this java.awt.event.MouseListener method
       */
      public void mouseReleased(MouseEvent e) {
      }

      /**
       * Invoked when the mouse enters a component.
       * @param e MouseEvent
       * @todo Implement this java.awt.event.MouseListener method
       */
      public void mouseEntered(MouseEvent e) {
      }

      /**
       * Invoked when the mouse exits a component.
       * @param e MouseEvent
       * @todo Implement this java.awt.event.MouseListener method
       */
      public void mouseExited(MouseEvent e) {
      }
    }

    posted @ 2006-02-19 17:59 sunfruit 閱讀(2752) | 評論 (10)編輯 收藏

    [JAVA]用戶自定義事件監聽

        --sunfruit

        用戶自定義事件

       

    User defined Event listeners java

    All of us who have used java.awt.event package in either applets
    or in Frames or in swing JFrame, shall agree to the fact that event
    propagation and listener concept is very very useful for capturing
    any action initiated either by user or by system, should be caught
    at the right place and without unneccessarily wasting time traversing
    through all the way from begining to end of source code just to know
    any takers for this event.



    This concept is implemented in form of MouseEvent, KeyEvent, WindowEvent so on so forth.

    JDK has given us a handle for creating our own event object and as well
    as event handling framework using java.util.EventObject and java.util.EventListener.

    You can imagine a scenario whereby you have to write an application, in
    which a email notification feature in a forum.

    Whenever a special event takes place , then your have to notify all the users
    who have registered themselves for this program.

    One solution is to use a Database and query all the users from the table
    and send notification to each and every user.
    But this is more of Database centric approach like old days thick client
    and server model.

    Think about the overhead on database and instead another solution is
    to create an event notification framework, whereby you have to create
    your own version of Event Object and Event Listeners.

    Event object represents the special event and all the users who register
    themselves for the event implements this Event listener.

    Let us take a more deeper plunge into this:

    1. Create a Demo event by creating a DemoEvent.java file that
    extends to java.util.EventObject.

    This class has a constructor that takes the event originator object (DemoSource).
    and a method getSource(), that gives the reference to the object that originated
    this event.

    DemoEvent.java
    
    package demo.listener;
    
    import java.util.EventObject;
    
    public class DemoEvent extends EventObject
    {
    	Object obj;
    	public DemoEvent(Object source)
    	{
    		super(source);
    		obj = source;
    
    	}
    	public Object getSource()
    	{
    		return obj;
    	}
    	public void say()
    	{
    		System.out.println("This is say method...");
    	}
    
    }
    
    


    2. Create the source of event notification file DemoSource.java
    It has a java.util.Vector that acts like a repository for storing all the
    listeners to the events this source provides.

    It has two other common method such as addListener(..) is to add any
    new user to this event.

    And notifyDemoEvent(..) is to alert all the users about this perticular event
    occurance.

    DemoEvent.java
    
    package demo.listener;
    import java.util.*;
    
    public class DemoSource
    {
    	private Vector repository = new Vector();
    	DemoListener dl;
    	public DemoSource()
    	{
    
    	}
    	public void addDemoListener(DemoListener dl)
    	{
    		repository.addElement(dl);
    	}
    	public void notifyDemoEvent()
    	{
    		Enumeration enum = repository.elements();
    		while(enum.hasMoreElements())
    		{
    			dl = (DemoListener)enum.nextElement();
    			dl.demoEvent(new DemoEvent(this));
    		}
    	}
    }
    
    


    3. Define a listener interface that extends to java.util.EventListener
    and contains the method for invoking the Event, here it is demoEvent(DemoEvent de).

    DemoListener.java
    
    package demo.listener;
    
    import java.util.EventListener;
    
    public interface DemoListener extends EventListener
    {
    	public void demoEvent(DemoEvent dm);
    
    }
    
    



    4. Define all the users, who want to listen to this events.
    These objects should implement DemoListener, to be able to
    capture the event propagated from DemoSource.java.

    Listener1.java
    
    package demo.listener;
    
    public class Listener1 implements DemoListener
    {
    	public void demoEvent(DemoEvent de)
    	{
    		System.out.println("Inside listener1...");
    	}
    }
    
    


    Listener2.java
    
    package demo.listener;
    
    public class Listener2 implements DemoListener
    {
    	public void demoEvent(DemoEvent de)
    	{
    		System.out.println("Inside listener2...");
    	}
    }
    
    

    Listener3.java
    
    package demo.listener;
    
    public class Listener3 implements DemoListener
    {
    	public void demoEvent(DemoEvent de)
    	{
    		System.out.println("Inside listener3...");
    	}
    }
    
    


    5. Now it time to write the client for testing this Framework.
    Create a client such as TestDemo.java and create a DemoSource
    object and all the users such as Listener1, Listener2, Listener3.
    And add all these listeners to the demo source by using the addDemoListener(..).
    When the notifyDemoEvent(..) is called on the demo source object,
    the event gets notified to all the users (listener1, listener2, listener3)
    and  the  output comes out to be

    Inside listener1...
    Inside listener2...
    Inside listener3...


    TestDemo.java
    
    package demo.listener;
    
    public class TestDemo
    {
    	DemoSource ds;
    
    	public TestDemo()
    	{
    		try{
    			ds = new DemoSource();
    			Listener1 l1 = new Listener1();
    			Listener2 l2 = new Listener2();
    			Listener3 l3 = new Listener3();
    
    			ds.addDemoListener(l1);
    			ds.addDemoListener(l2);
    			ds.addDemoListener(l3);
    
    			ds.notifyDemoEvent();
    
    		}catch(Exception ex){ex.printStackTrace();}
    	}
    
    	public static void main(String args[])
    	{
    		new TestDemo();
    	}
    }
    

    posted @ 2006-02-19 17:58 sunfruit 閱讀(3539) | 評論 (0)編輯 收藏

    僅列出標題
    共11頁: First 上一頁 3 4 5 6 7 8 9 10 11 下一頁 
    主站蜘蛛池模板: 亚洲国产成人久久综合野外| 久久精品夜色噜噜亚洲A∨| 色吊丝免费观看网站| 亚洲精品夜夜夜妓女网| 国产在线jyzzjyzz免费麻豆| 美女羞羞视频免费网站| 亚洲欧洲国产日韩精品| 在线观看免费精品国产| 午夜视频在线免费观看| 亚洲成AV人片在WWW| 亚洲精品蜜桃久久久久久| 成年美女黄网站色大免费视频| 丰满妇女做a级毛片免费观看| 深夜a级毛片免费视频| 女人18毛片a级毛片免费| 中文字幕免费观看视频| 亚洲一区二区三区高清不卡| 亚洲愉拍99热成人精品热久久| 国产一卡二卡3卡四卡免费| 亚洲国产精品成人综合久久久| 国产免费观看视频| 国产精彩免费视频| 精品无码国产污污污免费网站国产| 亚洲精品中文字幕乱码影院| 亚洲一级片免费看| 免费观看理论片毛片| 十九岁在线观看免费完整版电影| 美国免费高清一级毛片| 亚洲成A∨人片在线观看无码| 久久乐国产精品亚洲综合| 成人性生免费视频| 91麻豆国产免费观看| 中文字幕成人免费高清在线视频| 亚洲熟女精品中文字幕| 亚洲首页在线观看| 亚洲精品美女久久777777| 亚洲国产人成中文幕一级二级| 天天摸夜夜摸成人免费视频 | 国产AV旡码专区亚洲AV苍井空| 亚洲精品无码久久久久| 亚洲av片一区二区三区|