1 / 96

More Coffee: Java API, Conventions, Precision, GUI, Applet

Review Java API and Reference Manuals, learn about Java Conventions, Precision and Data Format with DecimalFormat, Java and Windows Programming (GUI), and more about Applets.

arroyor
Download Presentation

More Coffee: Java API, Conventions, Precision, GUI, Applet

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. Programming in Java http://www.csie.nctu.edu.tw/~tsaiwn/java/ More Coffee 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw

  2. Outline • Review: Java API and Reference Manuals • More Coffee: Java Conventions, Java vs. C++ • Precision and Data Format, DecimalFormat • %?.?f -- Decimal Format again • Java and Windows Programming (GUI) • More about Applet

  3. Of course you can visit home of java: http://java.sun.com/

  4. Of course you can visit home of java: http://java.sun.com/

  5. Types of Java Programs • Applications • A standalone program just like a console applications for C/C++. • Applets • A plug-in program inside a web page. • Servlets (1997) • A plug-in program inside a web page but running on server side. • JSP (Java Server Page) (1999) • An HTML-like text program with Java code. • Similar to ASP and PHP.

  6. Java Interpreter Java Compiler Java Libraries Just in Time Compiler Runtime System Operating System Hardware Java Compile-interpret-execute Cycle Runtime environment (Java Platform) Compile time environment Class loader bytecode to verifier Java Source Java Virtual Machine Bytecodes move locally or through net Java bytecode (class) Java compiler does not generate machine code

  7. 喝咖啡, 講清楚, 說明白 (1/5) Java程式跟C++程式真的非常像。 • * 用 Java 寫的程式應該要以 .java 結尾, 用 Java 編譯器將之編譯成 .class 結尾的 bytecode 檔案以便能被 Java 的虛擬機直譯器(JVM Interpreter)來執行。 • 每一個 .java 程式的最外層依序為: (注意依序!) • 最多一個的 package 宣告(沒寫表示屬於 default package) (如前所述, Java 把一些相關的 class 一起放在一子目錄下叫做 package) • 可有不限數量的 import 指述以使程式中用到別的class的指述可寫得較為簡短 • 一個或多個 class 或 interface • 每一個 .java 程式內雖可有很多class, 但最多只可以有一個 public 的 class, 且這個程式檔名必須與該public 的 class 名稱相同, 大小寫也要一樣! 編譯完的 .class 檔之名稱也不可再改名。

  8. 喝咖啡, 講清楚, 說明白 (2/5) Java的命名原則(當然, 不遵守也不會怎樣啦! • -- class 和 interface 之名稱宜用名詞, 且每個英文單字的頭要大寫 例如 MyFirstProgram, BigAnimal, BigInteger • -- method 名稱宜用動詞, 第一個字母用小寫(Constructor例外), 其它單字的頭大寫 例如 getMySalary, doSomething, toString, print • -- 變數, 個體(object, 或稱物件) 的名稱也是第一個字母用小寫, 其它單字的頭大寫 例如 mySalary, myHeight, currentStudent, height • -- 原始型別的常數宜用全大寫, 必要時隔以底線號(underscore) 例如 MAX_LIMIT, MIN_LIMIT, NUMBER_OF_STUDENT • -- 個體(Object; 物件)常數可大小寫混用, 例如 Last_Student, LAST_Person

  9. 喝咖啡, 講清楚, 說明白 (3/5) Java有八大原始型態(Primitive Date Type) (Literal寫法與C/C++相同)! • 不知是巧合還是 .. 大陸有江八點, 台灣有八大行業, 八部二會, 阿Java 剛好有八種原始資料型態 :-) • 還有八仙過海, 江南八怪, 八大胡同, ㄟ..都是八, 真是傑克..阿太神奇了:-) boolean(1 bit, false, true), char(16 bits unsigned, Unicode), byte(8 bits), short(16 bits), int(32 bits), long(64 bits), float(32 bits), double(64 bits) • 注意3.14D 和 3.14 是 double, 3.14f 和 3.14F 是 float, 123L 是 long

  10. 喝咖啡, 講清楚, 說明白 (4/5) Java的 Array不同於 C/C++! Reference? Object? • Java中任何東東(包括Primitive Type)的 array 一律為 object, 只是個"reference" • 阿就是說array和任何object宣告後並不會自動creat, 一定要用 new 才能生出來 • 例如 int[] rgb = new int[3]; int month[] = new int[12]; • 又如 Stack x = new Stack( ); x.pop( ); Compare to C++: Stack x; x.pop( );

  11. 喝咖啡, 講清楚, 說明白 (5/5) Java的控制指述 (Control statements)與 C/C++ 大致相同, 除了: • Java 中 控制流程的運算式是boolean 運算式 (C/C++ 可為任何運算式)! -- 包括 if( ) 和 while( )的括號內, for(;;)括號中兩個分號中間都須為boolean運算式 -- 所以如果k是整數, if(k)... 在Java是錯的, 要寫成 if(k!=0)... • Loop 之前可帶有 Label, 以便讓break 和 continue 配合使用; 例如: haha: while(true){ for(...){ if(...) break haha; //跳到"//while尾"的下一statement } // ... 注意, break haha; 不是 break 到這喔 } // while 尾 Multi-Level break與 continue

  12. Precision 與 Data Format (p.1/5) ccsun5 testjava > cat -n TestPrecision.java 1 // TestPrecision.java -- CopyLeft by tsaiwn@csie.nctu.edu.tw 2 // to Test (1)precision, (2)computation rule for floating expression 3 // please compare to floatdbl.c in our C/C++ handouts 4 //Also test the format capability of the java.text.Format class 5 //It and it's subclasses provides data editing similar to printf() in C Lang. 6 import java.text.*; // Format, NumberFormat, DecimalFormat, ... 7 public class TestPrecision { 8 static final String f4dot2 = "0.00"; //Integer part at least one digit 9 private static String myformat(float x){ 10 DecimalFormat f = new DecimalFormat(" #######00.000####"); 參看java.lang.System 這 class 的 prototype

  13. Precision 與 Data Format (cont.2/5) 11 return f.format(x); //at least like 99.999 12 } 13 private static String myformat(double x){ // rewrite for double 14 DecimalFormat f = new DecimalFormat("########0.0000000"); 15 return f.format(x); // the above means f.setMaximumFractionDigits(7); 16 } 17 private static String myfm2(double x){ 18 DecimalFormat f = new DecimalFormat(f4dot2); 19 f.setMinimumIntegerDigits(5); // at least 5 digits in Integer part 20 return f.format(x); 21 } 22 public static void main( String p[]) { 23 float x, xdelta; 24 double y; long i; 25 x = (float)1234567.2; 26 xdelta = 0.0001f; 27 System.out.println("Before loop, x="+ x); 28 System.out.println(" (double)x="+ (double)x);

  14. Precision 與 Data Format (cont.3/5) 29 System.out.println(" ===" + myformat(x) ); 30 System.out.println("xdelta="+ myformat(xdelta)); 31 for(i=1; i<= 8000; i++){ 32 x = x + xdelta; /******/ 33 } 34 System.out.println(" After loop, x="+ x); 35 System.out.println(" (double)x="+ (double)x); 36 System.out.println("\nDo it again with double y ..."); 37 y = 1234567.2; 38 xdelta = 0.0001F; 39 System.out.println("Before loop, y="+ y); 40 System.out.println(" ===" + myformat(y) ); 41 for(i=1; i<= 8000; i++){ 42 y = y + xdelta; /*** promotion is allowed, not coercion ***/ 43 } /*** x = y; is not allowed ! ***/ 44 System.out.println(" After loop, y="+ y); 45 System.out.println(" ===" + myformat(y) );

  15. Precision 與 Data Format (cont.4/5) 45 System.out.println(" ===" + myformat(y) ); 46 System.out.println(" == myfm2() has format pattern"+ 47 " \"0.00 with modification through its method\"=="); 48 System.out.println(" which means %4.2f in C Language"); 49 System.out.println(" myfm2(123.564)=" + myfm2(123.564) ); 50 System.out.println(" myfm2(123.566)=" + myfm2(123.566) ); 51 System.out.println(" myfm2(123.565)=" + myfm2(123.565) ); 52 System.out.println(" 注意不是真的四捨五入, 這符合IEEE754的規定"); 53 System.out.println("3849==="+ new DecimalFormat("##000000").format(3849)); 54 } 55 } ccsun5 testjava > /usr/local/jdk/jdk1.2.2/bin/javac TestPrecision.java sjhuang has replaced srchao on pts/17 from openbsd. ccsun5 testjava > /usr/local/jdk/jdk1.2.2/bin/java TestPrecision Before loop, x=1234567.2 (double)x=1234567.25 === 1234567.250

  16. Precision 與 Data Format (cont.5/5) xdelta= 00.0001 After loop, x=1234567.2 (double)x=1234567.25 Do it again with double y ... Before loop, y=1234567.2 ===1234567.2000000 After loop, y=1234568.0000005036 ===1234568.0000005 == myfm2() has format pattern "0.00 with modification through its method"== which means %4.2f in C Language myfm2(123.564)=00123.56 myfm2(123.566)=00123.57 myfm2(123.565)=00123.56 注意不是真的四捨五入, 這符合IEEE754的規定 3849===003849 ccsun5 testjava > exit

  17. Method Detail in DecimalFormat format public StringBufferformat(doublenumber, StringBufferresult, FieldPositionfieldPosition) Description copied from class: NumberFormat Specialization of format. Overrides: format in class NumberFormat Tags copied from class: NumberFormat See Also: Format.format(java.lang.Object)

  18. Java : 再喝咖啡, 再靠近一點 ..(1/6) Java 雖然抄自 C++ 語言, 但是還是有許多改變需要注意。 • Java 的運算符號(operator)及其運算次序跟C++相同 (修正一些C/C++未規定清楚的), 且&&與 || 也有short cut evaluation(或稱short circuit或lazy evaluation)的特性。 • Java 沒有指標, 保留了“參考”(reference), 但是一些規定跟C++ 也不太一樣。 • 八大原始型態(Primitive type) 的單一變數不能宣告出“參考” • 在C++中可以 long salary; long& pay=salary; 使pay與salary參考同位址, 再來寫 pay=38; 就如同寫 salary=38; 但是在Java中沒有辦法這樣做。 • 事實上, 除了八大原始型態的單一變數外, 所有其它變數都是"參考", 包括八大原始型態的array(陣列)變數也都是"參考"(即陣列是object) • 既然array是參考, 宣告時不能宣告它的size 例如 int x[60]; 是錯的, 只能寫 int x[]; 或 int[] x; 之後再用 如 x = new int[60]; 使 x 參考到新建的 array object, • 當然宣告時也可以順便new啦, 如 int x[]= new int[60]; 注意 int [ ] x, y; 相當於 int x[ ], y[ ];

  19. Java : 再喝咖啡, 再靠近一點 ..(2/6) Java 雖然抄自 C++ 語言, 但是還是有許多改變需要注意。 複習: • Java中任何東東(包括原始型態)的 array 一律為 object, 只是個"reference" , 就是說array和任何object宣告後並不會自動creat, 一定要用 new 才能生出來 • 注意對"參考"所做的assignment是改變"參考", 不是改變其參考的物件! • -- 例如假設已有 Student 這class, Student x = new Student("張三"); Student y = new Student("李四"); y = x; // 這使 y 和 x 都參考到 "張三", 而"李四"就不見了! // 因為Java有Auto Garbage Collection 的能力, "李四"所佔記憶體會被自動回收

  20. Java : 再喝咖啡, 再靠近一點 ..(3/6) Java 雖然抄自 C++ 語言, 但是還是有許多改變需要注意。 • 注意如上的 y=x; 是複製"參考"而已, 若你是要複製出另一份object,必須用clone() 這method, 例如: y = x.clone(); 這樣會複製出另一個“張三”, 則y和x各參考到不同的object(不同的“張三”)。但是在 x 所屬的class 也須重寫clone( ) 這 method才有用! • 再注意對"參考"所做的比較也只是比較"參考"本身, 不是比較其參考到的object, 所以如果x, y 仍如上述的Student, 則 if(x == y) ... // 是說如果 x 和y 參考到同一個 object ... 若是要比較其object 的內容是否相同, 須用equals()這method, 例如: if(x.equals(y)) ... // x與y這兩個object之內容是否相同? 當然你也要在其class重寫 equals() 這個 method 才有用! • // 阿不過 String 這 class 的 equals() 已是比字串內容

  21. Java : 再喝咖啡, 再靠近一點 ..(4/6) class, object, reference • object(物件,物體) 是 class(類別) 的一個 Instance (範例, 案例)。 • reference(參考)可參考到object, 有點類似指標, 但不是指標, 不可對它作運算。 • base class的reference可以參考到它所衍生出的class之object • 在super class中除了帶有final的function外, 都為 virtual(用於Polymorphism) 萬海歸宗: Java 程式所有Class都源自 Object (沒寫extends就是extends Object)

  22. Java : 再喝咖啡, 再靠近一點 ..(5/6) Class (static) variables vs. Instance variables • class中帶有 static 的變數不附屬於任一object, 所以又稱 class 變數。 注意寫法跟 C++不同: C++中寫 Student::TOTAL表示Student這class中的TOTAL這field 在 Java 中要寫成 Student.TOTAL (注意在此 Student 是 class) • 不帶有static的變數使用時一定要配合object, 故稱Instance variables • 常數就是帶有final的變數, 表示不可再被改變的變數; 不是用 const這保留字。

  23. Java : 再喝咖啡, 再靠近一點 ..(6/6) Class (static) methods vs. Instance methods • class中帶有 static 的函數(方法)不附屬於任一object, 所以稱 class method • 注意使用時也是要寫成ClassName.method( ) 而不是C++ 的 ClassName::method( ) • 數學函數: java.lang.Math 這class提供很多常用的數學函數 -- 包括abs, min, max, ceil, floor, round, random, sqrt 以及三角函數等。 -- 還有PI 值以及自然對數E 兩個double常數 (Math.PI和 Math.E)。

  24. 再進一步模擬 %?.?f (p1/4) ccsun5 testformat > cat -n TestFormat.java 1 // TestFormat.java -- CopyLeft by tsaiwn@csie.nctu.edu.tw 2 // to test the format capability of the java.text.Format class 3 import java.text.*; // Format, NumberFormat, DecimalFormat, ... 4 public class TestFormat { 5 static final String myformat = "##############0.0######"; 6 private static String myfmt(double x, int t, int p){ 7 DecimalFormat s = new DecimalFormat(myformat); 8 s.setMaximumFractionDigits(p); 9 s.setMinimumFractionDigits(p); 10 int n = t - p - 1; if(n<0) n=1; // one position for decimal point 11 s.setMaximumIntegerDigits(n); // %t.pf 12 s.setMinimumIntegerDigits(1); // at least 1 digits in Integer part 13 String ans = s.format(x); 14 while(ans.length( ) < t) ans = " "+ans; 15 return ans; 16 }

  25. 再進一步模擬 %?.?f (p2/4) 17 private static String myfmt(double x, int t){ 18 return myfmt(x, t, 0); 19 } 20 private static String myfmt(double x) { 21 return myfmt(x, 15, 6); // use %15.6f 22 } 23 public static void main( String p[]) { 24 float x, xdelta; 25 double y; long i; 26 x = (float)1234567.2; 27 xdelta = 0.0001f; 28 System.out.println("Before loop, x="+ myfmt(x,14,5)); // %14.5f 29 System.out.println(" (double)x="+ myfmt((double)x,14,5)); 30 System.out.println("xdelta="+ myfmt(xdelta,9,5)); // %9.5f 31 for(i=1; i<= 8000; i++) { 32 x = x + xdelta; /*** 會怎樣 ? 注意 float 用 32 bits ***/ 33 } Function name Overloading 共寫了三個 myfmt( )

  26. 再進一步模擬 %?.?f (p3/4) 34 System.out.println(" After loop, x="+ myfmt(x,14,5)); 35 System.out.println(" (double)x="+ myfmt(x,14,5)); 36 System.out.println("\nDo it again with double y ..."); 37 y = 1234567.2; 38 xdelta = 0.0001F; 39 System.out.println("Before loop, y="+ myfmt(y,14,5)); 40 for(i=1; i<= 8000; i++){ 41 y = y + xdelta; /*** promotion is allowed, not coercion ***/ 42 } /*** x = y; is not allowed ! ***/ 43 System.out.println(" After loop, y="+ myfmt(y,14,5)); 44 System.out.println(" ="+ myfmt(y,14)); 45 System.out.println(" ="+ myfmt(y)); 46 System.out.println(" myfmt(12345, 7)=" + myfmt(12345, 7) ); 47 System.out.println("3849==="+ new DecimalFormat("##000000").format(3849)); 48 } 49 } 到底使用哪個 myfmt( ) ?

  27. 再進一步模擬 %?.?f (p4/4) ccsun5 testformat > /usr/local/jdk/jdk1.2.2/bin/javac TestFormat.java ccsun5 testformat > /usr/local/jdk/jdk1.2.2/bin/java TestFormat Before loop, x= 1234567.25000 (double)x= 1234567.25000 xdelta= 0.00010 After loop, x= 1234567.25000 (double)x= 1234567.25000 Do it again with double y ... Before loop, y= 1234567.20000 After loop, y= 1234568.00000 = 1234568 = 1234568.000001 myfmt(12345, 7)= 12345 3849===003849 ccsun5 testformat > /// 若要直接生出 a.out 則可以這樣: gcj --main=TestFormat TestFormat.java (確定環境變數 LD_LIBRARY_PATH 含有/usr/local/lib ) 注意 Loop 前後答案一樣

  28. 卡布奇諾 --- 咖啡之香醇在於它裝在小杯子中(大杯就沒味道了:-) 用 Java 來練習 Windows Programming 是個不錯的主意。 • Windows 程式就是使用 GUI (Graphical User Interface; 圖形式使用者介面) 來和使用者溝通的程式。 GUI 要唸作 "Goo-EE" ! • Windows Programming 主要的基本招式包括: (a) GUI 元件 (Component) 的使用與擺放 (b) GUI 事件 (Event) 的處理 • GUI 元件有些人稱為"Control" (控制), UNIX系統上稱為 Widget, 都是指一個可讓使用者用來與程式溝通的圖樣。使用者可用滑鼠點按該圖樣的某處, 或是用鍵盤輸入資料給該圖樣。

  29. AWT Widgets • Widgets are components such as: • -buttons, text fields, menus, etc. • These widgets are used to make up a Graphical User Interface (GUI) • The java.awt package provides a set of classes for • implementing a wide variety of widgets. • These classes are platform independent, so a menu in a Java • program will look like a Windows menu on a PC running • Windows, a Mac menu on a Macintosh, and a Motif menu on • a Unix machine - all with the same code. • We construct a GUI by placing components within a container. • - normally, there are only two types of containers used: • Frame - creates a complete window • Panel - a container and a component • - Several Panels may be within a Frame, and within each Panel may be • several components.

  30. 用 Java 來練習 Windows Programming 是不錯的主意。(1/3) • 在 java.awt這 package 中提供了許多GUI 元件程式庫, awt是抽象視窗工具箱 (Abstract Window Toolkit)的英文縮寫。利用這些元件就可輕易的做出選單(Menu), 捲動式選項列(List), 標籤(Label), 按鈕(Button), 勾選盒(Check box), 彈出式選擇鈕(Choice)等等的圖形介面。 • JDK 1.2 開始增加了更好用的GUI類別庫JFC 和 Swing 圖形庫。 • JFC (Java Foundation Classes)提供了更漂亮更好用的GUI 元件, 例如 JTree 可用來製作“檔案總管”, JFC 共有五百多個 Class, 這些Class 都用大寫的 J 開頭, 所以頭兩個字母都是大寫, 如JButton。 然而到目前(2002年)為止, 微軟的 IE 和 Netscape 的瀏覽器都尚未支援JDK1.2, 若不裝 Plug-in 或抓必要的 Classes 就無法看, 所以若要寫 Applet 阿就通常都嘛 不敢用 JFC 的東東, 不然就只能用 appletviewer 自己觀賞。

  31. 用 Java 來練習 Windows Programming 是不錯的主意。(2/3) • GUI Programming 通常就是做這些事: (a) 宣告並建立控制元件, 必要時設定元件一些屬性, 如: Dialog dd = new Dialog(null, "Hello"); dd.setSize(240,180); Button btn = new Button("Bye"); dd.add(btn); // 把 btn 放入 dd 這對話盒容器中 (b) 必要時要求不同的擺設經理(Layout Manager)以便用不同方式來擺放元件。 --有些容器元件有內定的擺設經理, 你可用setLayout()改掉 --常用的擺設經理有FlowLayout, BorderLayout, GridLayout 當然還有很多, 它們都implements一個叫做LayoutManager的介面 (c) 向某些監聽經理(Listener)註冊GUI元件相關的事件, 以便當有 event 發生 時會通知我們寫的程式(就是叫用我們寫的程式)。例如: btn.addActionListener(this); // 目前這(this)class要有implements // .. ActionListener //這是說若有 btn 的event請呼叫目前這class裡寫的actionPerformed() (d) 撰寫事件處理程式, 阿就是在 (c)中所述有事件發生時會叫用的程式。 這些程式依不同監聽經理的要求都有特定的程式名稱, 例如: 向 ActionListener註冊後有事件發生則會叫用 actionPerformed()函數。

  32. 用 Java 來練習 Windows Programming 是不錯的主意。(3/3) • 所有的 GUI 元件都源自一個叫做 java.awt.Component的 class • Component 之下衍生出八大類別: Button, Canvas, Checkbox, Choice, Label, List, Scrollbar, TextComponent • 其中 TextComponent又衍生出TextArea, TextField兩類別。 • 還有, Component也衍生出Container以便衍生出容器視窗元件, Container生出的類別包括 Panel, ScrollPane, Window 。 • 另外, JComponent 也是由 java.awt.Container 直接生出來的, JComponent又生出其他一堆 J 字輩的 classes。(Swing Library) • 當然還有很多 J 字輩的 classes不是由 JComponent生出的。

  33. Component Label Canvas Container TextComponent Button Panel Window TextField TextArea Frame Dialog Applet The Component Class • The Component class is an “abstract” class.

  34. Applet is a Panel More about Applet • Applet is a Panel • Panel is a Container • Container is a Component

  35. Applet is a Panel • Panel is a Container • Container is a Component

  36. Panels • A Panel is a subclass of Container and is used to group components together. • A Panelis a Container - it has a default constructor • - Panel () • builds a Panel object with its layout set to FlowLayout • - in version 1.1 • Panel (LayoutManager layout) • allows you to specify the LayoutManager to be used in the Panel • object • Layouts are responsible for arranging the Components • within a Container • The most important of the Container layout methods is: • - void setLayout( LayoutManager layout) • allows you to change the LayoutManager of this Container.

  37. Nesting Panels • To create more complex GUIs, panels may be nested (panels inside of panels). • Here’s a segment of code: • - Panel p1 = new Panel(new BoderLayout( )); • Panel p2 = new Panel(); • p2.add(new Button()); • p1.add(“South”, p2); //add p2 inside p1 • add(p1); //add p1 to the applet

  38. A Simple Applet (1/2) import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { ddItem("preparing for unloading..."); }

  39. A Simple Applet (2/2) void addItem(String newWord) { System.out.println(newWord); //on Java console buffer.append(newWord); repaint( ); } public void paint(Graphics g) { //Draw a Rectangle in the applet's display area. g.drawRect(0, 0, size().width-1, size().height-1); //Draw the current string inside the rectangle. g.drawString(buffer.toString( ), 5, 15); } }

  40. The Life Cycle of an Applet (1/2) • Loading the Applet • When an applet is loaded, here's what happens: • An instance of the applet class is created. • The applet initializes itself. init( ) • The applet starts running. start( ) • Leaving and Returning to the Applet's Page • Leaves the page -- go to another page -- the applet stopping itself. stop( ) • Returns to the page, the applet can start itself again. start( ) • The same sequence occurs when the user iconifies and then reopens the window that contains the applet. • Reloading the Applet • Reload applets -- unloading the applet and then loading it again. • Before unloaded, applet stop itself and then to perform a final cleanup. • Applet can release any resources it holds. • Quitting the Browser • Applet stop itself and do final cleanup before the browser exits.

  41. The Life Cycle of an Applet (2/2) • Summary • An applet can react to major events in the following ways: • It can initialize itself. • It can start running. • It can stop running. • It can perform a final cleanup, in preparation for being unloaded. ( destroy ) • Note: • Use Netscape to try this. • IE is not working.

  42. Drawing and Event Handling • paint • The basic display method. • update • A method you can use along with paint to improve drawing performance. • The default one will clear the screen and then call paint().  So, this may cause blinking. class Simple extends Applet { //. . . public void paint(Graphics g) { //. . . } //. . . }

  43. Applets inherit a group of event-handling methods (e.g., addMouseListener(this)) from the Component class. import java.awt.event.MouseListener; import java.awt.event.MouseEvent; . . . Public class Simlpe extends Appletimplements MouseListener{ . . . Public void init( ){ addMouseListener(this); . . . } . . . Public void mouseClicked(MouseEvent event){ addItem(“click!…”); } . . . }

  44. Pre-Made UI Components • Buttons (java.awt.Button) • Checkboxes (java.awt.Checkbox) • Single-line text fields (java.awt.TextField) • Larger text display and editing areas (java.awt.TextArea) • Labels (java.awt.Label) • Lists (java.awt.List) • Pop-up lists of choices (java.awt.Choice) • Sliders and scrollbars (java.awt.Scrollbar) • Drawing areas (java.awt.Canvas) • Menus (java.awt.Menu,java.awt.MenuItem, java.awt.CheckboxMenuItem) • Containers (java.awt.Panel, java.awt.Window and its subclasses) GUI : Graphical User Interface

More Related