Applets Chapter 5
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
Applets • Đượ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 • 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
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()
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
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()
Life cycle of an Applet Contd… Redraw Applet Destroy Applet Start state init( ) Applet Born paint( ) start( ) stop( ) destroy( ) Applet Working Initialization state Applet Displayed Idle State Applet Destroyed
Creating an Applet • 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 • An applet is compiled using the Java compiler: javac • javac filename.java
A simple applet import java.awt.*; import java.applet.*; publicclassSimple extends Applet { String str; publicvoid init() //-inoge { str = "Java is interesting!"; } publicvoid 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> importjava.awt.*; import java.applet.*; import javax.swing.JLabel; publicclassSimple extendsApplet{ String str; JLabel g; publicvoidinit(){ str = "Java is interesting!"; g= new JLabel (str); add(g); } } import java.awt.Graphics; publicclassSimple extendsApplet { String str; publicvoid paint(Graphics g){ str = "Java is interesting!"; g.drawString(str, 50, 50); } }
A simple applet: Execution
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 importjava.awt.*; import java.applet.*; publicclassSimple extendsApplet { Image img; publicvoidinit() { img=getImage(getCodeBase(),"cafe.gif"); } publicvoid paint(Graphics g) { g.drawImage(img,20,20,this); } }
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>
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
Example <html> <applet code = ImageDemo width = 150 height = 150> <param name = "image" value = “cafe.gif"> </applet> </html> import java.awt.*; import java.applet.*; publicclassImageDemo extends Applet { Image img; publicvoidinit() { String imagename = getParameter("image"); img = getImage(getCodeBase(),imagename); } publicvoid paint(Graphics g) { g.drawImage(img,20,20,this); } } img =getImage(getCodeBase(), "cafe.gif");
Applets vs. Standard
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
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
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} } }
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; } }
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) { x3 = e.getX(); x4 = e.getY(); repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}
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; } } }
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
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
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) hinh=0; repaint(); return true; } }
Font class • 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. • java.awt.Font class is used to set or retrieve fonts.
Example /* /*<applet code = FontDemo width = 400 height = 400> </applet>*/ import java.applet.*; import java.awt.*; publicclassFontDemo extends Applet { publicvoid 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); } }
FontMetrics class • 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
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); } }
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.
Color class • Objects of Color class can be constructed as shown: • Color a = newColor(255,255,0); • Color b = newColor(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 • java.awt.Color class is used to add color to applications and applets.
AudioClip class • Void loop() • Void play() • Void stop() • AudioClip getAudioClip
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 (); } } }
Ứ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)
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); } }
Summary Applet • An Appletis 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.