溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java中怎么實(shí)現(xiàn)事件和監(jiān)聽器

發(fā)布時(shí)間:2021-07-01 16:25:51 來源:億速云 閱讀:140 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Java中怎么實(shí)現(xiàn)事件和監(jiān)聽器,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

事件監(jiān)聽器是經(jīng)??梢杂龅降囊环N設(shè)計(jì)模式,一般用在這樣一種場(chǎng)景下:當(dāng)模塊的一部分A在完成后需要通知其他的軟件模塊B,而等待通知的模塊B在事先不需要采用輪詢的方式來查看另一個(gè)模塊A是否通知自己。即,當(dāng)某事件發(fā)生,則監(jiān)聽器立刻就知道了該事件。這種模式大量的應(yīng)用在GUI設(shè)計(jì)中,比如按鈕的點(diǎn)擊,狀態(tài)欄上狀態(tài)的改變等等。

接口的設(shè)計(jì)

我們需要一個(gè)對(duì)事件(event)的抽象,同樣需要一個(gè)對(duì)監(jiān)聽器(listener)的抽象。我們可以把接口抽的很簡(jiǎn)單:

這個(gè)是事件源的接口,只需要提供一個(gè)可以獲取事件類型的方法即可:

package listenerdemo.framework;   /**   * @author juntao.qiu   */ public interface EventListener {      /**       * handle the event when it raise       * @param event       */     public void handleEvent(EventSource event);  }

監(jiān)聽器接口,提供一個(gè)當(dāng)事件發(fā)生后的處理方法即可:

package listenerdemo.framework;   public interface EventSource {      public final int EVENT_TIMEOUT = 1;      public final int EVENT_OVERFLOW = 2;       /**       * get an integer to identify a special event       * @return       */     public int getEventType();  }

實(shí)例化事件

我們舉一個(gè)實(shí)現(xiàn)了事件源接口(EventSource)的類TimeoutEvent 來說明如何使用事件監(jiān)聽器模型:

package listenerdemo;   import listenerdemo.framework.*;   public class TimeOutEvent implements EventSource{      private int type;       public TimeOutEvent(){          this.type = EventSource.EVENT_TIMEOUT;;      }            public int getEventType() {          return this.type;      }   }

這個(gè)事件的類型為EVENT_TIMEOUT, 當(dāng)操作超時(shí)時(shí)觸發(fā)該事件,我們假設(shè)這樣一個(gè)場(chǎng)景:一個(gè)定時(shí)器T, 先設(shè)置這個(gè)定時(shí)器的時(shí)間為t,當(dāng)t到時(shí)后,則觸發(fā)一個(gè)超時(shí)事件,當(dāng)然,事件是需要監(jiān)聽器來監(jiān)聽才有意義的。我們看看這個(gè)定時(shí)器的實(shí)現(xiàn):

package listenerdemo;   import listenerdemo.framework.*;   /**   * @author juntao.qiu   */ public class Timer extends Thread{      private EventListener listener;      private int sleepSeconds;       public Timer(int seconds){          this.sleepSeconds = seconds;      }       public void setEventListener(EventListener listener){          this.listener = listener;      }            public void run(){          for(int i = sleepSeconds;i>0;i--){              try {                  Thread.sleep(1000);              } catch (InterruptedException ex) {                  System.err.println(ex.getMessage());              }          }                    raiseTimeoutEvent();//raise一個(gè)TimeOut事件給監(jiān)聽器      }       private void raiseTimeoutEvent(){          this.listener.handleEvent(new TimeOutEvent());      }  }

使用事件及其監(jiān)聽器

在類Tester的execute()方法中,我們先設(shè)置一個(gè)定時(shí)器,這個(gè)定時(shí)器初始化為3秒,設(shè)置好定時(shí)器后,程序進(jìn)入一個(gè)while(true)循環(huán)中,當(dāng)定時(shí)器到時(shí)后,它會(huì)發(fā)送一個(gè)timeout事件給當(dāng)前線程Tester,此時(shí)我們可以設(shè)置execute中的while條件為false,退出死循環(huán)。流程很清晰了,我們來看看代碼:

package listenerdemo;   import listenerdemo.framework.*;   /**   * @author juntao.qiu   */ public class EventListenerTester implements EventListener{      private boolean loop = true;       public void execute(){          Timer timer = new Timer(3);//初始化一個(gè)定時(shí)器          timer.setEventListener(this);//設(shè)置本類為監(jiān)聽器          timer.start();                    while(loop){              try{                  Thread.sleep(1000);                  System.out.println("still in while(true) loop");              }catch(Exception e){                  System.err.println(e.getMessage());              }          }           System.out.println("interupted by time out event");      }    //實(shí)現(xiàn)了EventListener接口      public void handleEvent(EventSource event) {          int eType = event.getEventType();          switch(eType){//判斷事件類型,我們可以有很多種的事件              case EventSource.EVENT_TIMEOUT:                  this.loop = false;                  break;              case EventSource.EVENT_OVERFLOW:                  break;              default:                  this.loop = true;                  break;          }      }       public static void main(String[] args){          EventListenerTester tester = new EventListenerTester();          tester.execute();      }   }

運(yùn)行結(jié)果如下:
run:
still in while(true) loop
still in while(true) loop
still in while(true) loop

關(guān)于Java中怎么實(shí)現(xiàn)事件和監(jiān)聽器就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI