1 / 12

事件處理

事件處理. Java 的事件處理是採取「委派事件模式 (delegation event model) 」。 事件對象: 事件傾聽者 (event listener) 通常會讓包含「事件來源者」的物件來擔任 事件來源者 (event source) 事件處理者. 委派事件模式 - 運作流程. AWTEvent 事件類別關係圖. 事件傾聽者的繼承關係. 事件與傾聽者類別的 method. 物件與可能觸發事件類別的對應關係. 練習 1- 視窗關閉按鈕. import java.awt.*; import java.awt.event .*;

dean-jordan
Download Presentation

事件處理

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 事件處理

  2. Java的事件處理是採取「委派事件模式(delegation event model)」。 • 事件對象: • 事件傾聽者(event listener) • 通常會讓包含「事件來源者」的物件來擔任 • 事件來源者(event source) • 事件處理者

  3. 委派事件模式-運作流程

  4. AWTEvent事件類別關係圖

  5. 事件傾聽者的繼承關係

  6. 事件與傾聽者類別的method

  7. 物件與可能觸發事件類別的對應關係

  8. 練習1-視窗關閉按鈕 import java.awt.*; import java.awt.event.*; class Example_Event1 { static Frame frm=new Frame("Action Event"); public static void main(String args[]) { Button btn=new Button("Click Me"); frm.setLayout(new FlowLayout()); frm.setSize(200,150); frm.setLocation(200,300); frm.add(btn); frm.setVisible(true); //此上部份只有視窗物件 //承下頁

  9. 練習1-視窗關閉按鈕 //續上頁 //此部份事件處理 //在frm加入一個視窗的傾聽者(addWindowListener), 用於註冊視窗關閉的按鈕 //事件處理者為windowCloasing(WindowEvent e), 做關閉離開System.exit(0) frm.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); } }

  10. 練習2-加入event import java.awt.*; import java.awt.event.*; class Example_Event2 { static Frame frm=new Frame("Action Event"); public static void main(String args[]) { Button btn=new Button("Click Me"); MyListenerlis=new MyListener(); //宣告傾聽者物件 btn.addActionListener(lis); //加入傾聽者註冊至按鈕btn frm.setLayout(new FlowLayout()); frm.setSize(200,150); frm.setLocation(200,300); frm.add(btn); frm.setVisible(true); }

  11. 練習2-加入event //續上頁 public static class MyListenerimplements ActionListener //將MyListener實作成事件處理 { public void actionPerformed(ActionEvent e) { frm.setBackground(Color.yellow); //改變視窗frm的背景顏色為黃色 } } }

  12. 輸入:TEST 按下Done 練習3

More Related