Download presentation
Presentation is loading. Please wait.
1
Chapter 5 Applets
2
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 class FontMetrics class Color class
3
Applets 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 java.applet.Applet cung cấp mọi chức năng đã được cài đặt trước phục vụ cho việc thực thi của các ct ứng dụng nhúng applet. Applet cung cấp chức năng: các tp GUI và các Container được nhúng vào Applet để tạo ra gd đhọa Các thao tác thực hiện của applet được viế đè trong paint()
4
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()
5
Chu kỳ sống của Applet 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
6
Chu kỳ sống của Applet 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()
7
Life cycle of an Applet Contd…
Start state Redraw Applet Destroy Applet init( ) Applet Born start( ) paint( ) stop( ) destroy( ) Applet Working Initialization state Applet Displayed Idle State Applet Destroyed
9
Creating an Applet An applet is compiled using the Java compiler: javac 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
10
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.drawString(str, 50, 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); } import java.awt.Graphics; public class Simple extends Applet { String str; public void paint(Graphics g){ str = "Java is interesting!"; g.drawString(str, 50, 50); } Có thể chạy applet trực tiếp trên Eclipse Hoặc Mở IE
11
A simple applet: Execution
Có thể chạy applet trực tiếp trên Eclipse Hoặc Mở IE
12
Displaying images using Applets
Các lớp: Image; Graphics Phương thức: getCodeBase() URL của applet getImage() trả về một đối tượng Image có thể vẽ trên màn hình drawImage() lấy bốn tham số – đối tượng Image, vị trí gồm toạ độ x và y, đối tượng kiểu ImageObserver import java.awt.*; import java.applet.*; public class Simple extends Applet { Image img; public void init() { img =getImage(getCodeBase(),"cafe.gif"); } public void paint(Graphics g) { g.drawImage(img,20,20,this);
13
APPLET tag <APPLET CODE = ClassFile width=x height=y //tên tệp thực thi applet [CODEBASE = URLDirectory] //xác định vị trí tệp từ xa [ARCHIVE = JarFileName] //Các tệp thực thi đặt vào tệp Jar [OBJECT = SerializeAppletFile]// Các object thực hiện tuần tự [NAME = AnotherAppletName] [ALIGN = AligmentOnPage] …. > [<PARA NAME = para1 [VALUE = para_value1]>] [<PARA NAME = para2 [VALUE = para_value2]>] … [<PARA NAME = paran [VALUE = para_valuen]>] </APPLET> OBJECT của HTML giống APPLET Dùng CODE thì khong dùng OBJECTvà ngược lại
14
Truyền tham số 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: getParameter()trả về một chuỗi
15
Example import java.awt.*; import java.applet.*;
<html> <applet code = ImageDemo width = 150 height = 150> <param name = "image" value = “cafe.gif"> </applet> </html> import java.awt.*; import java.applet.*; public class ImageDemo extends Applet { Image img; public void init() { String imagename = getParameter("image"); img = getImage(getCodeBase(),imagename); } public void paint(Graphics g) { g.drawImage(img,20,20,this); img =getImage(getCodeBase(), "cafe.gif");
16
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
17
Applets and GUI 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à FlowLayout 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 Pictorial hình ảnh
18
Xử lý các sự kiện với applet
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
19
Ex: xử lý button import java.awt.*; import java.awt.event.*; import java.applet.*; public class Simple extends Applet implements ActionListener { Label lbl1, lbl2, lblKq; TextField txt1, txt2; Button btnAccept, btnThoat; public void init() {this.setLayout(new GridLayout(6,2)); lbl1 = new Label("Nguoi thu nhat:"); this.add(lbl1); txt1 = new TextField(); this.add(txt1); lbl2 = new Label("Nguoi thu hai:"); this.add(lbl2); txt2 = new TextField(); this.add(txt2); lblKq = new Label(); this.add(lblKq); this.add(new Label()); // Các nút nhấn btnAccept = new Button("Accept"); btnAccept.addActionListener(this); this.add(btnAccept); btnThoat = new Button("Thoat"); btnThoat.addActionListener(this); this.add(btnThoat); } /* Phương thức xửlí sựkiện nútđược nhấn */ public void actionPerformed(ActionEvent ae){ String kq=""; if(ae.getSource() == btnAccept) // kq = txt1.getText() + " và " + txt2.getText(); if(ae.getSource() == btnThoat) // Thoát khỏi chương trình System.exit(0); // Thayđổi nội dung kết quả lblKq.setText("Chao mung 2 ban " + kq); repaint(); // Vẽlại cácđối tượng} Viets nút thoát chương trình: system.exit(0);
20
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 MouseListener, MouseMotionListener { int x1, y1, x2, y2; public void init() setLayout(new FlowLayout()); setBounds(100,100,300,300); addMouseListener(this); addMouseMotionListener(this); this.setVisible(true); } public void mouseClicked(MouseEvent e) public void mousePressed(MouseEvent e) x1 = e.getX(); y1 = e.getY(); public void mouseMoved(MouseEvent e) {} public void mouseReleased(MouseEvent e) { x2 = e.getX(); y2 = e.getY(); repaint(); } public void mouseEntered(MouseEvent e) public void mouseDragged(MouseEvent e) public void mouseExited(MouseEvent e) public void paint(Graphics g) g.drawRect(x1, y1, x2-x1, y2-y1); x2 = 0; y2 = 0; Rê chuột và vẽ hcn
21
Example 2: Xử lý Button, Mouse
/* <applet code=Painting width=400 height=400> </applet> */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class Painting extends Applet implements ActionListener, MouseListener { Button bdraw = new Button("Draw Rectangle"); int count = 0,x1,x2,x3,x4; public void init() BorderLayout border = new BorderLayout(); setLayout(border); add(bdraw, BorderLayout.PAGE_END); bdraw.addActionListener(this); addMouseListener(this); this.setVisible(true); } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { x1 = e.getX(); x2 = e.getY(); } public void mouseMove(MouseEvent e) x3 = e.getX(); x4 = e.getY(); repaint(); public void mouseReleased(MouseEvent e) public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) Nhấn button để Rê chuột vẽ hcn
22
Example Contd… public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand(); if("Draw Rectangle".equals(str)) count = 1; repaint( ); } public void paint(Graphics g) if(count == 1) g.drawRect(x1,x2,(x3-x1),(x4-x2)); x3 = x4 = 0;
23
Graphics class 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
24
Method in Graphic class
Hỗ trợ vẽ các hình: drawLine, drawRect, draw3DRect, drawOval, drawArc Tô màu: fillRect, fillRoundRect, fillOval, fillArc Đa giác: constructor: Polygon drawPolygon fillPolygon
25
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.drawLine(35,160, 70, 150); break; case 1: g.drawRect(35,160, 70, 150); break; case 2: g.drawRoundRect(35,160, 70, 150,90,200); break; case 3: g.drawOval(20,50, 170, 250); break; case 4: g.drawArc(35,160, 70, 150,210,150); break; public boolean action(Event e, Object o){ ++hinh; if (hinh==5) repaint(); return true;
26
Font class 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.
27
Example /* /*<applet code = FontDemo width = 400 height = 400>
import java.applet.*; import java.awt.*; public class FontDemo extends Applet { public void paint(Graphics g) String quote = "Attitude is the mind’s paintbrush"; Font objFont = new Font("Georgia",Font.ITALIC,20); g.setFont(objFont); g.drawString(quote,20,20); }
28
FontMetrics class In such a case, the FontMetrics class proves useful.
At times, it is necessary to know the attributes of fonts used within a program. In such a case, the FontMetrics class proves useful. Commonly used methods of FontMetrics class: int stringWidth(String s) – returns full width of string int charWidth(char c) – returns width of that character int getHeight() – returns total height of the font
29
Example /* <applet code= TextCentre width=400 height=400>
import java.applet.*; import java.awt.*; public class TextCentre extends Applet { public void paint(Graphics g) String myquote = "Happiness is an attitude."; Font objFont = new Font("Times New Roman" , Font.BOLD|Font.ITALIC , 24); FontMetrics fm = getFontMetrics(objFont); g.setFont(objFont); int numx = (getSize().width - fm.stringWidth(myquote))/2; int numy = getSize().height/2; g.drawString(myquote,numx,numy); }
30
Determining Available Fonts
We should always know which fonts are available on the machine. We can use a method called getAvailableFontFamilyNames() defined in the GraphicsEnvironment class. The syntax of the method is as follows: String[] getAvailableFontFamilyNames(): returns an array of Strings that contains the names of the available font families. Font[] getAllFonts(): returns an array of Font objects for all the available fonts.
31
Color class 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,255,0); Color b = new Color(0.907F,2F,0F); To change or set colors for a component : void setColor(Color) of Graphics class void setForeground(Color) of Component class ,inherited by various components void setBackground(Color) of Component class ,inherited by various components
32
AudioClip class Void loop() Void play() Void stop()
AudioClip getAudioClip
33
JApplet trong Swing import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JAppletDemo 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.addActionListener (new ButtonListener()); label = new JLabel ("Pushes: " + Integer.toString (pushes)); Container cp = getContentPane(); cp.setBackground (Color.yellow); cp.setLayout (new FlowLayout()); cp.add (push); cp.add (label); setSize (APPLET_WIDTH, APPLET_HEIGHT); } private class ButtonListener implements ActionListener public void actionPerformed (ActionEvent event) pushes++; label.setText("Pushes: " + Integer.toString (pushes)); repaint ();
34
Ứ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, ObjFr Gọi phương thức add: add(component) ex, ObjFr.add(dlap)
35
Ex: ứng dụng kết hợp import java.applet.Applet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class app_dlap extends Applet implements ActionListener { Button a = new Button("OK"); Button b=new Button("Exit"); TextField x=new TextField(10); TextField y=new TextField(10); public void init () resize(300,100); add(a); a.addActionListener(this); add(b); b.addActionListener(this); add(x); add(y); } public static void main (String args[]) app_dlap dlap = new app_dlap(); Frame ObjFr = new Frame("Ung dung doc lap - Applet"); ObjFr.setLayout(new FlowLayout()); ObjFr.resize(300,100); dlap.init(); ObjFr.add(dlap); ObjFr.setVisible(true); public void actionPerformed(ActionEvent e) { if (e.getSource() == a) System.out.println("Hello"); else System.exit(0);
36
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 FlowLayout. Images can be drawn on an applet by means of the paint(), getImage() and drawImage() 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.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.