Chapter 5. 2.java applet
-
Upload
cong-thanh-nguyen -
Category
Technology
-
view
1.164 -
download
2
Transcript of Chapter 5. 2.java applet
AppletsChapter 5
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
Objectives
2
Đượ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
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
3
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()
Applets class
4
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
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ỷ.
5
◦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()
Chu kỳ sống của Applet The methods are as follows:
6
Redraw Applet
stop( )
Start statestart(
)paint( )
Life cycle of an Applet Contd…
Applet Workin
g
Applet Born
Applet Displaye
d Idle State
Applet Destroyed
Initialization state
destroy( )
Destroy
Appletinit( )
7
8
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
Creating an Applet An applet is compiled using the Java
compiler: javac javac filename.java
9
A simple appletimport 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);
}}
10
<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);
}}
A simple applet: Execution
11
Displaying images using Appletsimport 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);
}}
12
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
<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>
APPLET tag
13
Truyền tham số
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
Các tham số cho phép người dùng kiểm soát những nhân tố của applet
Example
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);
}}
<html><applet code = ImageDemo width = 150 height = 150><param name = "image" value = “cafe.gif"></applet></html>
15
img =getImage(getCodeBase(), "cafe.gif");
Applets vs. Standard
16
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 WebCá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
Applets and GUI
17
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
Xử lý các sự kiện với applet
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
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
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ìnhSystem.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}}}
Ex: xử lý button
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 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; } }
20
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){}
21
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) { x3 = e.getX(); x4 = e.getY();
repaint(); }public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}
Example Contd…
22
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; } }}
Graphics class is a part of the java.awt package.
It has to be imported into the program.
Graphics class
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
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
Method in Graphic class
24
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)hinh=0;repaint();return true;}
}
Ex: vehinh
25
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.
Font class
java.awt.Font class is used to set or retrieve fonts.
26
/* /*<applet code = FontDemo width = 400 height = 400></applet>*/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); }}
Example
27
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
FontMetrics class At times, it is necessary to know the
attributes of fonts used within a program.
28
Example/*<applet code= TextCentre width=400 height=400></applet>*/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); }}
29
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.
Determining Available Fonts
30
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
Color class java.awt.Color class is used to add
color to applications and applets.
31
Void loop() Void play() Void stop() AudioClip getAudioClip
AudioClip class
32
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 ();
} }}
JApplet trong Swing
33
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ộngEx, 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)
Ứng dụng kết hợp
34
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);}
}
Ex: ứng dụng kết hợp
35
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.
Summary Applet
36