第六章、設計Java Applet - 物件導向程式設計

文章推薦指數: 80 %
投票人數:10人

event(事件):. event是一種用來描述狀態改變的物件。

當使用者與GUI介面連續互動時,將會有一系列的event產生。

例如按下一個button ... 物件導向程式設計     第六章、設計JavaApplet     授課教師:陳慶瀚 WWW :http://www.miat.ee.isu.edu.tw/java E-mail:[email protected]       6.8 事件驅動程式設計  6.8.1委任式事件模型(DelegationEventModel) 一個source可以產生和送出Event給一個或多個Listener,每一個Listener總是隨時等待接收event,一旦接收到一個event,Listener就會立即處理它並傳回結果。

任何一個使用者介面元件都可以委任這個程序模型來處理事件。

event(事件): event是一種用來描述狀態改變的物件。

當使用者與GUI介面連續互動時,將會有一系列的event產生。

例如按下一個button,從鍵盤輸入一個字元,從一個list box選擇一個item,或是click一下滑鼠。

eventsource(事件來源): source是一個產生event的物件,它可以產生一種或多種不同的事件,一個Source必須先註冊(register)才能夠委任listener來處理它的事件,每一個event都有它自己的註冊方法(成員函式),標準型態為: publicvoidaddTypeListener(TypeListener el) 例如註冊一個鍵盤事件listener的成員函式為:     addKeyListener() 而註冊一個滑鼠移動事件的listener的成員函式為:    addMouseMotionListener() 某些source可以允許註冊多種listener,其型態為:     publicvoid addTypeListener(TypeListenerel) 如果想要解除註冊,可以使用     publicvoid removeTypeListener(TypeListenerel) eventsource(事件來源): 一個listener是一個等待被event通知的物件。

使用listener有兩個條件,第一listener必須先被註冊才能使用。

第二必須定義相關成員函式以便接收和處理事件。

所有listener的成員函式都宣告在java.awt.event的package中。

6.8.2event物件類別 所有Java語言的event物件類別都繼承自EventObject ,包括awt所有GUI元件的event物件類別AWTEvent。

EventObject有兩個成員函式:getSource()和toString().   java.awt.event 主要的event事件類別     Event Class Description   ActionEvent Generatedwhenabuttonis pressed,alistitemisdouble-clicked,oramenuitemis selected. AdjustmentEvent Generatedwhenascrollbar ismanipulated. ComponentEvent Generatedwhenacomponent ishidden,moved,resized,orbecomesvisible. ContainerEvent Generatedwhenacomponent isaddedtoorremovedfromacontainer. FocusEvent Generatedwhenacomponent gainsorloseskeyboardfocus. InputEvent Abstractsuperclassforall componentinputeventclasses. ItemEvent Generatedwhenacheckbox orlistitemisclicked;alsooccurswhenachoiceselectionismadeora checkablemenuitemisselectedordeselected. KeyEvent Generatedwheninputis receivedfromthekeyboard. MouseEvent Generatedwhenthemouseis dragged,moved,clicked,pressed,orreleased;alsogeneratedwhenthemouse entersorexitsacomponent. TextEvent Generatedwhenthevalueof atextareaortextfieldischanged. WindowEvent Generatedwhenawindowis activated,closed,deactivated,deiconified,iconified,opened,or quit. 6.8.3SourcesofEvents物件類別     EventSource Description   Button Generatesactioneventswhenthebutton ispressed. Checkbox Generatesitemeventswhenthecheck boxisselectedordeselected. Choice Generatesitemeventswhenthechoice ischanged. List Generatesactioneventswhenanitemis double-clicked;generatesitemeventswhenanitemisselectedor deselected. MenuItem Generatesactioneventswhenamenu itemisselected;generatesitemeventswhenacheckablemenuitemisselected ordeselected. Scrollbar Generatesadjustmenteventswhenthe scrollbarismanipulated. Textcomponents Generatestexteventswhentheuser entersacharacter. Window Generateswindoweventswhenawindow isactivated,closed,deactivated,deiconified,iconified,opened,or quit. 6.8.4EventListener物件類別:Interfaces     EventListener Interfaces   Interface Description   ActionListener Definesonemethodtoreceiveaction events. AdjustmentListener Definesonemethodtoreceive adjustmentevents. ComponentListener Definesfourmethodstorecognizewhen acomponentishidden,moved,resized,orshown. ContainerListener Definestwomethodstorecognizewhena componentisaddedtoorremovedfromacontainer. FocusListener Definestwomethodstorecognizewhena componentgainsorloseskeyboardfocus. ItemListener Definesonemethodtorecognizewhen thestateofanitemchanges. KeyListener Definesthreemethodstorecognizewhen akeyispressed,released,ortyped. MouseListener Definesfivemethodstorecognizewhen themouseisclicked,entersacomponent,exitsacomponent,ispressed,oris released. MouseMotionListener Definestwomethodstorecognizewhen themouseisdraggedormoved. TextListener Definesonemethodtorecognizewhena textvaluechanges. WindowListener Definessevenmethodstorecognizewhen awindowisactivated,closed,deactivated,deiconified,iconified,opened,or quit. 6.8.5滑鼠事件驅動程式設計 為了掌握滑鼠得事件,我們需定義兩個物件類別: ─MouseListenerinterfaces ─ MouseMotionListener interfaces 下列範例程式用來展示滑鼠事件的處理: //Demonstratethemouseeventhandlers.importjava.awt.*;import java.awt.event.*;importjava.applet.*; publicclassex9extends Applet  implementsMouseListener,MouseMotionListener{    Stringmsg="";  intmouseX=0,mouseY=0;//coordinatesof mouse   publicvoidinit()  {     addMouseListener(this);      addMouseMotionListener(this);  }   //Handlemouse clicked.  publicvoidmouseClicked(MouseEventme)  {    //save coordinates    mouseX=0;    mouseY=10;    msg="滑鼠咬我!";     repaint();  }   //Handlemouseentered.  publicvoid mouseEntered(MouseEventme)  {    //savecoordinates    mouseX= 0;    mouseY=10;    msg="滑鼠進來了!";    repaint();  }    //Handlemouseexited.  publicvoidmouseExited(MouseEventme)   {    //savecoordinates    mouseX=0;    mouseY=10;     msg="滑鼠出去了!";    repaint();  }   //Handlebutton pressed.  publicvoidmousePressed(MouseEventme)  {    //save coordinates    mouseX=me.getX();    mouseY=me.getY();    msg ="按下";    repaint();  }   //Handlebuttonreleased.  publicvoidmouseReleased(MouseEventme)   {    //savecoordinates    mouseX=me.getX();    mouseY= me.getY();    msg="放開";    repaint();  }   //Handle mousedragged.  publicvoidmouseDragged(MouseEventme)  {    // savecoordinates    mouseX=me.getX();    mouseY=me.getY();     msg="*";    showStatus("滑鼠現在位置:"+mouseX+","+mouseY);     repaint();  }   //Handlemousemoved.  publicvoid mouseMoved(MouseEventme)  {    //showstatus     showStatus("滑鼠現在位置:"+me.getX()+","+me.getY());  }    //DisplaymsginappletwindowatcurrentX,Ylocation.  public voidpaint(Graphicsg)  {    g.drawString(msg,mouseX,mouseY);   }   } 6.8.6Keyboard事件處理 importjava.awt.*;importjava.awt.event.*;importjava.applet.*;  publicclassSimpleKeyextendsAppletimplementsKeyListener{    Stringmsg="";  intX=10,Y=20;//outputcoordinates    publicvoidinit()  {    addKeyListener(this);     requestFocus();//requestinputfocus  }   publicvoid keyPressed(KeyEventke)  {    showStatus("Key按下");  }    publicvoidkeyReleased(KeyEventke)  {     showStatus("Key放開");  }   publicvoidkeyTyped(KeyEvent ke)  {    msg+=ke.getKeyChar();    repaint();  }    //Displaykeystrokes.  publicvoidpaint(Graphicsg)  {     g.drawString(msg,X,Y);  }   } 如果想使用一些特殊的功能鍵,如,,...,, ...,範例程式如下: importjava.awt.*;importjava.awt.event.*;importjava.applet.*; publicclassKeyEventsextendsAppletimplementsKeyListener{    Stringmsg="";  intX=10,Y=20;//outputcoordinates    publicvoidinit()  {    addKeyListener(this);     requestFocus();//requestinputfocus  }   publicvoid keyPressed(KeyEventke)  {    showStatus("Key按下");     int key=ke.getKeyCode();    switch(key)    {      case KeyEvent.VK_F1:        msg+="";        break;       caseKeyEvent.VK_F2:        msg+="";         break;      caseKeyEvent.VK_F3:        msg+= "";        break;      caseKeyEvent.VK_PAGE_DOWN:         msg+="";        break;      case KeyEvent.VK_PAGE_UP:        msg+="";        break;       caseKeyEvent.VK_LEFT:        msg+="";         break;      caseKeyEvent.VK_RIGHT:        msg+= "";        break;    }    repaint();  }    publicvoidkeyReleased(KeyEventke)   {     showStatus("Key放開");  }   publicvoidkeyTyped(KeyEvent ke)  {    msg+=ke.getKeyChar();    repaint();  }    //Displaykeystrokes.  publicvoidpaint(Graphicsg)  {     g.drawString(msg,X,Y);  }   }    物件導向程式設計 義守大學電機系陳慶瀚 2001.12.18  



請為這篇文章評分?