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.
More Coffee: Java API, Conventions, Precision, GUI, Applet
Une image / un lien ci-dessous est fourni (tel quel) pour télécharger la présentation
Politique de téléchargement : le contenu du site vous est fourni TEL QUEL pour votre information et votre usage personnel ; il ne peut être vendu, concédé sous licence ni partagé sur d’autres sites sans l’accord de son auteur.Le contenu vous est fourni TEL QUEL, pour votre information et votre usage personnel uniquement.Téléchargez la présentation en cliquant sur ce lien.Lors du téléchargement, si vous ne parvenez pas à télécharger une présentation, l’éditeur a peut-être supprimé le fichier de son serveur.Pendant le téléchargement, si vous ne parvenez pas à obtenir une présentation, le fichier a peut-être été supprimé par l’éditeur.
F I N
Plus de contenu associé
Transcription de la présentation
Programming in Java http://www.csie.nctu.edu.tw/~tsaiwn/java/ More Coffee 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw
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
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.
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
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
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);
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) );
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
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
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)
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[ ];
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 的能力, "李四"所佔記憶體會被自動回收
再進一步模擬 %?.?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 }
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.
Component Label Canvas Container TextComponent Button Panel Window TextField TextArea Frame Dialog Applet The Component Class • The Component class is an “abstract” class.
Applet is a Panel More about Applet • Applet is a Panel • Panel is a Container • Container is a Component
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.
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
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..."); }
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); } }
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.
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.
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) { //. . . } //. . . }
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!…”); } . . . }
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
Connexion au compte
Connectez-vous pour publier votre contenu sur SlideServe.