Chapter 5 Applets Objectives Define an applet Differentiate
Chapter 5 Applets
Objectives Define an applet Differentiate between Java Applications and Java Applets Create an applet Identify how parameters are passed to applets Discuss event handling with Applets Explain Classes such as ◦ ◦ Graphics class Font. Metrics class Color class 2
Applets n Applet là một chương trình Java được nhúng vào một trang HTML và thực thi trên một trình duyệt hỗ trợ Java Được tạo ra từ lớp con của lớp java. applet. Applet Một số trình duyệt hỗ trợ Java: Internet Explorer, Netscape Communicator 3
Applets class Lớp Applet là một thành phần của AWT, nằm gói khác java. awt Lớp java. applet. Applet cung cấp mọi chức năng phục vụ việc thực thi các ứng dụng nhúng applet: ◦ Các thành phần GUI và các Container được nhúng vào 1 applet. ◦ Các thao tác thực hiện của applet được viết đè trong hàm paint() 4
Chu kỳ sống của Applet n Chu kỳ sống của một đối tượng xác định những giai đoạn mà đối tượng phải trải qua từ khi đối tượng được tạo ra cho đến lúc bị huỷ. Applet định nghĩa cấu trúc của nó từ bốn sự kiện xảy ra trong quá trình thực thi Với mỗi sự kiện, một phương thức tự động được gọi 5
Chu kỳ sống của Applet n The methods are as follows: ◦ init(): called during initialization ◦ start(): starts the applet once it is initialized ◦ stop(): used to pause the execution of an applet ◦ destroy(): used to destroy the applet ◦ Phương thức paint() dùng để hiển thị một đường, văn bản hay hình ảnh lên màn hình ◦ Khi applet được vẽ lại sau khi đã được vẽ một lần, phương thức repaint() được dùng ◦ Khi xử lý các đối tượng điều khiển ko cần Paint() 6
Life cycle of an Applet Contd… init( ) Applet Born Initialization state Start state Redraw Applet start( ) paint( ) Destroy Applet stop( ) destroy( ) Applet Working Applet Displayed Idle State Applet Destroyed 7
8
Creating an Applet n An applet is compiled using the Java compiler: javac n javac filename. java Create a HTML page to display the applet <html> <applet code=“filename. class” width=200 height=200> </applet> </html> -> File name, ex: abc. html Run Applet: ◦ Command Prompt: appletviewer abc. html. ◦ Open with IE ◦ Test in IDE Eclipse directly 9
A simple applet import java. awt. *; import java. applet. *; public class Simple extends Applet { String str; public void init() //-inoge { str = "Java is interesting!"; } public void paint(Graphics g){ g. draw. String(str, 50); } } import java. awt. Graphics; public class Simple extends Applet { String str; public void paint(Graphics g){ str = "Java is interesting!"; g. draw. String(str, 50); } } <HTML> <HEAD> <TITLE>The first my Web</TITLE> </HEAD> <APPLET code="Simple. class" width=200 height=200 > </APPLET> </HTML> import java. awt. *; import java. applet. *; import javax. swing. JLabel; public class Simple extends Applet { String str; JLabel g; public void init(){ str = "Java is interesting!"; g= new JLabel (str); add(g); } } 10
A simple applet: Execution 11
Displaying images using Applets v Các lớp: import java. awt. *; import java. applet. *; n Image; public class Simple extends Applet { n Graphics Image img; v Phương thức: public void init() { img =get. Image(get. Code. Base(), "cafe. gif"); - get. Code. Base() URL } của applet public void paint(Graphics g) { - get. Image() trả về một g. draw. Image(img, 20, this); } đối tượng Image có thể } vẽ trên màn hình - draw. Image() lấy bốn tham số – đối tượng Image, vị trí gồm toạ độ x và y, đối tượng kiểu Image. Observer 12
APPLET tag <APPLET CODE = Class. File width=x height=y //tên tệp thực thi applet [CODEBASE = URLDirectory] //xác định vị trí tệp từ xa [ARCHIVE = Jar. File. Name] //Các tệp thực thi đặt vào tệp Jar [OBJECT = Serialize. Applet. File]// Các object thực hiện tuần tự [NAME = Another. Applet. Name] [ALIGN = Aligment. On. Page] …. > [<PARA NAME = para 1 [VALUE = para_value 1]>] [<PARA NAME = para 2 [VALUE = para_value 2]>] … [<PARA NAME = paran [VALUE = para_valuen]>] </APPLET> 13
Truyền tham số n Các tham số cho phép người dùng kiểm soát những nhân tố của applet Các tham số được truyền cho applet dùng thẻ <param> trong file HTML Giá trị tham số được rút trích trong applet dùng phương thức: get. Parameter()trả về một chuỗi
Example <html> <applet code = Image. Demo width = 150 height = 150> <param name = "image" value = “cafe. gif"> </applet> </html> import java. awt. *; import java. applet. *; public class Image. Demo extends Applet { Image img; public void init() { img =get. Image(get. Code. Base(), String imagename = get. Parameter("image"); "cafe. gif"); img = get. Image(get. Code. Base(), imagename); } public void paint(Graphics g) { g. draw. Image(img, 20, this); } } 15
Applets vs. Standard function Standard Applet Ứng dụng: trên Server/Client. Công cụ phát triển software Được thiết kế để ứng dụng trên web Khai báo: Là lớp con của bất kỳ lớp nào trong các gói Phải là lớp con của Applet GUI Tùy chọn Do trình Web Cách thức thực hiện Bắt đầu bằng hàm main() Bắt đầu bằng hàm init() Dữ liệu vào Thông qua tham số dòng lệnh Các tham số đặt trong tệp HTML Cách nạp và chạy CT Nạp bằng dòng lệnh và thực hiện nhờ trình biên dịch Java Thông qua trang web Yêu cầu bộ nhớ Bộ nhớ tối thiểu Bộ nhớ dành cho cả trình duyệt và applet 16
Applets and GUI được dùng để tạo ra một giao diện có nhiều tranh ảnh để dễ làm việc Layout mặc định của applet là Flow. Layout Những đối tượng điều khiển có thể tạo ra ◦ Cách tạo tương tự trong AWT ◦ Khác là không cần tạo thành phần (Frame) để chứa các điều khiển 17
Xử lý các sự kiện với applet n Click hay nhấn phím Enter trên những thành phần GUI sẽ tạo ra một sự kiện Trong khi thiết kế applet ta cần bẫy các sự kiện này và cung cấp những hành vi thích hợp được thực hiện để đáp ứng mỗi sự kiện Thủ tục theo sau khi một sự kiện được tạo ra ◦ Xác định loại sự kiện ◦ Xác định thành phần tạo ra sự kiện ◦ Viết lệnh xử lý sự kiện
Ex: xử lý button import java. awt. *; import java. awt. event. *; import java. applet. *; public class Simple extends Applet implements Action. Listener { Label lbl 1, lbl 2, lbl. Kq; Text. Field txt 1, txt 2; Button btn. Accept, btn. Thoat; public void init() {this. set. Layout(new Grid. Layout(6, 2)); lbl 1 = new Label("Nguoi thu nhat: "); this. add(lbl 1); txt 1 = new Text. Field(); this. add(txt 1); lbl 2 = new Label("Nguoi thu hai: "); this. add(lbl 2); txt 2 = new Text. Field(); this. add(txt 2); lbl. Kq = new Label(); this. add(lbl. Kq); this. add(new Label()); // Các nút nhấn btn. Accept = new Button("Accept"); btn. Accept. add. Action. Listener(this); this. add(btn. Accept); btn. Thoat = new Button("Thoat"); btn. Thoat. add. Action. Listener(this); this. add(btn. Thoat); } /* Phương thức xửlí sựkiện nútđược nhấn */ public void action. Performed(Action. Event ae){ String kq=""; if(ae. get. Source() == btn. Accept) // kq = txt 1. get. Text() + " và " + txt 2. get. Text(); if(ae. get. Source() == btn. Thoat) // Thoát khỏi chương trình System. exit(0); // Thayđổi nội dung kết quả lbl. Kq. set. Text("Chao mung 2 ban " + kq); repaint(); // Vẽlại cácđối tượng} } } 19
Example: Xử lý MOuse /* <applet code = Mousey width = 400 height = 400> </applet>*/ import java. awt. *; import java. applet. *; import java. awt. event. *; public class Mousey extends Applet implements Mouse. Listener, Mouse. Motion. Listener { int x 1, y 1, x 2, y 2; public void init() { set. Layout(new Flow. Layout()); set. Bounds(100, 300, 300); add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); this. set. Visible(true); } public void mouse. Clicked(Mouse. Event e) { } public void mouse. Pressed(Mouse. Event e) { x 1 = e. get. X(); y 1 = e. get. Y(); } public void mouse. Moved(Mouse. Event e) {} public void mouse. Released(Mouse. Event e) { x 2 = e. get. X(); y 2 = e. get. Y(); repaint(); } public void mouse. Entered(Mouse. Event e) {} public void mouse. Dragged(Mouse. Event e) {} public void mouse. Exited(Mouse. Event e) {} public void paint(Graphics g) { g. draw. Rect(x 1, y 1, x 2 -x 1, y 2 -y 1); x 2 = 0; y 2 = 0; } } 20
Example 2: Xử lý Button, Mouse /* <applet code=Painting width=400 height=400> </applet> */ public void mouse. Pressed(Mouse. Event e) { x 1 = e. get. X(); x 2 = e. get. Y(); } import java. applet. *; public void mouse. Move(Mouse. Event e) import java. awt. *; { import java. awt. event. *; x 3 = e. get. X(); public class Painting extends Applet implements Action. Listener, x 4 = e. get. Y(); Mouse. Listener repaint(); { } Button bdraw = new Button("Draw Rectangle"); public void mouse. Released(Mouse. Event e) int count = 0, x 1, x 2, x 3, x 4; { public void init() x 3 = e. get. X(); { x 4 = e. get. Y(); Border. Layout border = new Border. Layout(); repaint(); set. Layout(border); } add(bdraw, Border. Layout. PAGE_END); public void mouse. Entered(Mouse. Event e) bdraw. add. Action. Listener(this); {} add. Mouse. Listener(this); public void mouse. Exited(Mouse. Event e) this. set. Visible(true); {} } public void mouse. Clicked(Mouse. Event e) {} 21
Example Contd… public void action. Performed(Action. Event e) { String str = e. get. Action. Command(); if("Draw Rectangle". equals(str)) { count = 1; repaint( ); } } public void paint(Graphics g) { if(count == 1) { g. draw. Rect(x 1, x 2, (x 3 -x 1), (x 4 -x 2)); x 3 = x 4 = 0; } } } 22
Graphics class is a part of the java. awt package. It has to be imported into the program. Thủ tục tổng quát để vẽ hình ảnh • Lấy URL hay đường dẫn đến hình ảnh được hiển thị • Quyết định vị trí hình ảnh hiển thị • Cung cấp những thông tin này dùng một phương thức thích hợp 23
Method in Graphic class Hỗ trợ vẽ các hình: ◦ draw. Line, ◦ draw. Rect, ◦ draw 3 DRect, ◦ draw. Oval, ◦ draw. Arc Tô màu: fill. Rect, fill. Round. Rect, fill. Oval, fill. Arc Đa giác: ◦ constructor: Polygon ◦ draw. Polygon ◦ fill. Polygon 24
Ex: vehinh import java. applet. *; import java. awt. *; public class vehinh extends Applet { int hinh; Button nut; public void init(){ hinh=0; nut= new Button("Hinh tiep: "); add(nut); } public void paint(Graphics g) { int num =5; switch (hinh){ case 0: g. draw. Line(35, 160, 70, 150); break; case 1: g. draw. Rect(35, 160, 70, 150); break; case 2: g. draw. Round. Rect(35, 160, 70, 150, 90, 200); break; case 3: g. draw. Oval(20, 50, 170, 250); break; case 4: g. draw. Arc(35, 160, 70, 150, 210, 150); break; } } public boolean action(Event e, Object o){ ++hinh; if (hinh==5) hinh=0; repaint(); return true; } } 25
Font class n java. awt. Font class is used to set or retrieve fonts. One of the constructor of the Font class is: ◦ public Font(String name, int style, int pointsize) name can be “Times New Roman”, “Arial” and so on. style can be Font. PLAIN, Font. BOLD, Font. ITALIC pointsize for fonts can be 11, 12, 14, 16 and so on. 26
Example /* /*<applet code = Font. Demo width = 400 height = 400> </applet>*/ import java. applet. *; import java. awt. *; public class Font. Demo extends Applet { public void paint(Graphics g) { String quote = "Attitude is the mind’s paintbrush"; Font obj. Font = new Font("Georgia", Font. ITALIC, 20); g. set. Font(obj. Font); g. draw. String(quote, 20); } } 27
Font. Metrics class n At times, it is necessary to know the attributes of fonts used within a program. In such a case, the Font. Metrics class proves useful. Commonly used methods of Font. Metrics class: ◦ int string. Width(String s) – returns full width of string ◦ int char. Width(char c) – returns width of that character ◦ int get. Height() – returns total height of the font 28
Example /* <applet code= Text. Centre width=400 height=400> </applet>*/ import java. applet. *; import java. awt. *; public class Text. Centre extends Applet { public void paint(Graphics g) { String myquote = "Happiness is an attitude. "; Font obj. Font = new Font("Times New Roman" , Font. BOLD|Font. ITALIC , 24); Font. Metrics fm = get. Font. Metrics(obj. Font); g. set. Font(obj. Font); int numx = (get. Size(). width - fm. string. Width(myquote))/2; int numy = get. Size(). height/2; g. draw. String(myquote, numx, numy); } } 29
Determining Available Fonts We should always know which fonts are available on the machine. We can use a method called get. Available. Font. Family. Names() defined in the Graphics. Environment class. The syntax of the method is as follows: ◦ String[] get. Available. Font. Family. Names(): returns an array of Strings that contains the names of the available font families. ◦ Font[] get. All. Fonts(): returns an array of Font objects for all the available fonts. 30
Color class n java. awt. Color class is used to add color to applications and applets. Objects of Color class can be constructed as shown : ◦ Color a = new Color(255, 0); ◦ Color b = new Color(0. 907 F, 2 F, 0 F); To change or set colors for a component : ◦ void set. Color(Color) of Graphics class ◦ void set. Foreground(Color) of Component class , inherited by various components ◦ void set. Background(Color) of Component class , inherited by various components 31
Audio. Clip class Void loop() Void play() Void stop() Audio. Clip get. Audio. Clip 32
JApplet trong Swing import java. awt. *; import java. awt. event. *; import javax. swing. *; public class JApplet. Demo extends JApplet { private int APPLET_WIDTH = 300, APPLET_HEIGHT = 35; private int pushes; private JLabel label; private JButton push; public void init () { pushes = 0; push = new JButton ("Push Me!"); push. add. Action. Listener (new Button. Listener()); label = new JLabel ("Pushes: " + Integer. to. String (pushes)); Container cp = get. Content. Pane(); cp. set. Background (Color. yellow); cp. set. Layout (new Flow. Layout()); cp. add (push); cp. add (label); set. Size (APPLET_WIDTH, APPLET_HEIGHT); } private class Button. Listener implements Action. Listener { public void action. Performed (Action. Event event) { pushes++; label. set. Text("Pushes: " + Integer. to. String (pushes)); repaint (); } } } 33
Ứng dụng kết hợp Kết hợp ứng dụng độc lập và Applet ◦ Định nghĩa lớp ứng dụng, kế thừa Applet ◦ Phải có hàm main() Tạo đối tượng thuộc lớp ứng dụng mở rộng Ex, dlap Gọi hàm init(): ex, dlap. init(); Tạo thành phần chứa các đối tượng (Frame) Ex, Obj. Fr Gọi phương thức add: add(component) ex, Obj. Fr. add(dlap) 34
Ex: ứng dụng kết hợp import java. applet. Applet; import java. awt. *; import java. awt. event. Action. Event; import java. awt. event. Action. Listener; public class app_dlap extends Applet implements Action. Listener { Button a = new Button("OK"); Button b=new Button("Exit"); Text. Field x=new Text. Field(10); Text. Field y=new Text. Field(10); public void init () { resize(300, 100); add(a); a. add. Action. Listener(this); add(b); b. add. Action. Listener(this); add(x); add(y); } public static void main (String args[]) { app_dlap = new app_dlap(); Frame Obj. Fr = new Frame("Ung dung doc lap - Applet"); Obj. Fr. set. Layout(new Flow. Layout()); Obj. Fr. resize(300, 100); dlap. init(); Obj. Fr. add(dlap); Obj. Fr. set. Visible(true); } public void action. Performed(Action. Event e) { if (e. get. Source() == a) System. out. println("Hello"); else System. exit(0); } } 35
Summary Applet An Applet is a Java program that can be executed with the help of a Java enabled browser. Every user-defined applet must extend the java. applet. Applet class. A user defined applets inherits all the methods of Applet class. <applet>. . </applet> tags are used within a HTML file to embed a class file. The default layout for an applet is Flow. Layout. Images can be drawn on an applet by means of the paint(), get. Image() and draw. Image() methods. Whenever the user performs an action such as moving the mouse, pressing a key, releasing the key and so on, an event is generated. We can make use of event handler classes and interfaces to handle these events. 36
- Slides: 36