UNIT SWINGS PDF
Document Details
Uploaded by WellInformedOnyx5709
CMR Technical Campus
A.kiran Kumar
Tags
Summary
This document provides an overview of programming concepts related to Java and GUI development, using Swing and AWT. It covers topics like GUI architecture, components, layout managers, event handling, and application design in Java.
Full Transcript
Prepared by A.kiran Kumar Assistant Professor CMRTC CSE Dept UNIT - V GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components, containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid...
Prepared by A.kiran Kumar Assistant Professor CMRTC CSE Dept UNIT - V GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture, components, containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid Layout, Card Layout, Grid Bag Layout. Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event classes, Handling mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner classes. A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and Applications, passing parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint example, Exploring Swing Controls- JLabel and Image Icon, JText Field, The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs. What is AWT? AWT: AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI window-based applications in Java. It was developed by heavily Sun Microsystems In 1995. The java.awt package contains component classes such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. AWT components are platform-dependent. For example an AWT GUI having a button would have a different look and feel across platforms like windows, Mac OS & Unix AWT components are heavy weight. Limitations of AWT:Dis-advantages 1. Awt components are heavy weight. 2. AWT Components are platform dependent. 3. The AWT programs increase the overhead on the JVM.Because They depend on files of local operating system in creating GUI. 4. The button does not support pictures. 5. tables and trees these important components are missing. What is Swing? Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. Swing Follows MVC architecture Swing Supports a Pluggable look and feels And Swing provides more powerful components such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc. Swing offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with drag-and-drop support. What is JFC The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications. Java Foundation classes represent a class library developed in java which is an extension to awt. It contains classes that are completely portable,since the entire JFC is developed in pure Java. JFC Components are light weight.It utilize min System resources. JFC Components have same look and Feel on all plattforms. JFC offers a rich set of Components with lot of features this is the reason JFC is very popular all over the world. Swing Features or characteristics Light Weight: Swing components are lightweight. The swing components are completely developed using java code. Platform Independent: Swing Components are Platform Independent. Rich Controls: Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls. Highly Customizable: Swing controls can be customized in a very easy way as visual apperance is independent of internal representation. Pluggable look-and feel: Swing based GUI Application look and feel can be changed at run time based on available values. Swing Class Hirarchy Difference Between AWT and SWING Swing classes : Object: All classes in Java are inherited from the object class. Component:A component is an object having a Graphical Representation That can be displayed on the Screen. Example of components:Buttons,Labels,CheckBoxes TextFields, RadioButtons, etc. are called components in Java. Container:The Container is a component in AWT that can contain other components.A container is like a screen where in we are placing components like buttons, text fields, checkbox etc. Ex: Jframe and JPanel. Swing Components: JLabel: It inherits JComponent class. It is used for placing text in a container. JButton: It is used to create a labelled button. It is useful to perform some action when the button is clicked. It inherits the AbstractButton class and is platform-independent. JTextField: It inherits the JTextComponent class where the user can type single line of text JTextArea: It inherits the JTextComponent class where user can enter multiple lines of text. JList: It inherits JComponent class, the JList represents the user a list of text items. JScrollBar: It is used to add scroll bar, both horizontal and vertical. JComboBox Class: It inherits the JComponent class and is used to select a value from a drop- down list. You can choose one and only one element from the list. JCheckbox: JCheckBox is used to create a checkbox, of which multiple checkboxes could be selected at the same time The user can select one or more options from a group of checkboxes. JRadioButton: RadioButton is used to select one option from multiple Options. Only one RadioButton selected at a time. JSlider JSlider is a component that lets the users select a value by sliding a knob within a specified interval. JTable JTable is used to create a regular two-dimensional table. The table can display data inside of it. In addition, the user can also edit the data. JMenu Class: It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar. Ex: We have a File menu, which includes of save, quit submenu, and Edit menu, including copy, cut, paste submenu, and Help menu JPasswordField : A JPasswordField object it is a text component specialized for password entry Swing Containers A container holds a group of components. It provides a space where a component can be managed and displayed. we can add components like JTextfield, JButton, Jcheckbox etc. There four Container they are : JPanel, JFrame and Jwindow and JDialog. 1.Jpanel :JPanel is a container that can store a group of components.It is lightweight container we can use Panels to partition the JFrame. Each panel groups several other components inside it. A JFrame can have more than one-JPanel and we can add components inside it. 2JFrame: A JFrame is a top-level window with a title ,menubar and a border.It is heavy weight container JFrame works like the main window where components like JLabels, JButtons, JTextfields are added to create a GUI. 3 JWindow: JWindow is a low level container and light weight container, by default it uses the BorderLayoutwith no borders no menubar and no title. 4. JDialog :The JDialog control represents a top level window with a border and a title used to take some form of input from the user. Creating a JFrame There are two ways to create a JFrame in Swing 1.By creating the Object of JFrame class. 2.By extending JFrame class. 2.By extending JFrame class. Layout Manager: Layout Manager: The LayoutManagers are used to arrange components in a particular order in a frame. The Java LayoutManagers control the positioning and size of the components in GUI forms. The Following classes represent the layout managers in java 1.FlowLayout 2.BorderLayout 3.CardLayout 4.GridLayout 5.GridBagLayout The above classes are present in the java.awt package 1.FlowLayout :FlowLayout is useful to arrange the components in a line or Sequence one after other. It is the Default Layout of the Applet or Panel. The FlowLayout arranges the components in a directional flow, either from left to right or from right to left. To create FlowLayout we use the following ways: Syntax: FlowLayout f=new FlowLayout(); FlowLayout f=new FlowLayout(int alignment) FlowLayout f=new FlowLayout(int alignment, int hgap,int vgap) 2. BorderLayout:The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area) may contain one component only. It is the default layout of a frame or window To create BorderLayout we use the following ways: Syntax: 1.BorderLayout f=new BorderLayout(); 2.BorderLayout f=new BorderLayout(int hgap,int vgap) Here hgap and vgap space between components. 3.GridLayout The GridLayout is used to arrange the components in a rectangular grid. One component is displayed in each rectangle. The container is divided in to equal-sized rectangles. To create GridLayout we use the following ways: Syntax: 1.GridLayout obj=new GridLayout(); 2.GridLayout obj=new GridLayout(int rows, int columns) 3.GridLayout obj=new GridLayout(int rows, int columns, int horizontalGap, int verticalGap) 4.CardLayout: Card Layout is used, when we want to see only one component at a time. It treats each component as a card that is why it is known as CardLayout. The container acts as a stack of cards. To create CardLayout we use the following ways: Syntax: CardLayout c=new CardLayout(); CardLayout c=new CardLayout (int hgap,int vgap) While adding components to the container we can use add() as c.add(“cardname” ,component); 5.GridBagLayout:GridBagLayout is a more flexible layout manager which allows the components to be arranged in rows and colums. GridBagLayout is used to align components vertically, horizontally. The components may not be of the same size.Each component occupies one or more cells known as its display area. With the help of constraints object we arrange component's display area on the grid. To create GridBagLayout we use the following ways: Syntax: 1.GridBagLayout obj=new GridBagLayout(); 2.GridBagConstraints cons=new GridBagConstraints(); 1.gridx and gridy They represent the row and column positions of the component at upper left corner of the component. 2. gridwidth and gridheight They specify the number of columns for (gridwidth) or rows for (gridheight) in the component display area. 3.fill: fill is useful to resize the component according to the space available in the display area. 4. ipadx and ipady: are useful to leave space horizontally and vertically Model-View-Controller (MVC) architecture The Model-View-Controller (MVC) is a design pattern in web application development. It is a way to organize our code. Swing uses the Model-view-Controller architecture (MVC) as the fundamental design behind each of its components. MVC represents the separation of the model of an object from its view and how it is controlled. The MVC pattern architecture consists of three layers: Model: The Model represents the data of the component. View: The look (the visual appearance) of the component. Controller: The Controller takes the input from the user on the view and reflects the changes in the Component’s data. MVC Architecture: Advantages of MVC Architecture The components are easy to maintain because there is less dependency. A model can be reused by multiple views that provides reusability of code. The developers can work with the three layers (Model, View, and Controller) simultaneously. Using MVC, the application becomes more understandable. Using MVC, each layer is maintained separately therefore we do not require to deal with massive code. The testing of application is easier. EventDelegationModel The modern approach for event processing is based on the EvenDelegation Model. It defines a standard and compatible mechanism to generate and process events in GUI. The key advantage of the Delegation Event Model is that the application logic is completely separated from the interface logic. In this model, a source generates an event and forwards it to one or more listeners. The listener waits until it receives an event. Once it receives the event, it is processed by the listener and returns it. Event Model is based on the following three components: Events Events Sources Event Listeners There are three participants in event delegation model in Java, Events: Event is an object that is generated when end user interacts with components,such as clicking a button, Mouse click etc. Ex: ActionEvent ,MouseEvent Events Sources:Event source is an object that generates an event and forwards it to one or more listeners. A source must register a listener to receive notifications for a specific event. Each event contains its registration method. Ex: JButton creates an Action Event How to register source with a listener Syntax: public void addTypeListener (TypeListener e1) Type is the name of the event, and e1 is a reference to the event listener. For ActionEvent we use addActionListener() to register. Ex: public void addActionListener(ActionListener e1) Event Listeners: An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it must be registered with a source. Second, it must implement the methods to receive and process the received notifications. Ex: ActionListener. MouseListener, KeyListener For example, the MouseMotionListener interface provides two methods when the mouse is dragged and moved. Any object can receive and process these events if it implements the MouseMotionListener interface. What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs. What is Event Event: Changing the state of an object is known as an event. For example, click on button, dragging mouse ,pressing the keys on keyboard etc. ▪ The java.awt.event package provides many event classes and Listener interfaces for event handling. What is Event Source? A source is an object that generates an event. There are various sources like buttons, checkboxes, list, menu-item, scrollbar, etc to generate events. A source must register to a listener to receive notifications for a specific event. Each event contains its registration method. To perform Event Handling, we need to register the source with the listener. Registering the Source With Listener Different Classes provide different registration methods. Syntax: public void addTypeListener (TypeListener e1) Type is the name of the event, and e1 is a reference to the event listener. For ActionEvent we use addActionListener() to register. Ex: public void addActionListener(ActionListener e1) Checkbox public void addItemListener(ItemListener a){} List public void addActionListener(ActionListener a){} public void addItemListener(ItemListener a){} Button public void addActionListener(ActionListener a){} MenuItem public void addActionListener(ActionListener a){} TextField public void addActionListener(ActionListener a){} public void addTextListener(TextListener a){} TextArea public void addTextListener(TextListener a){} Event Classes: Event classes are the classes that represent events 1. Action Event: The ActionEvent is generated when the button is clicked or the item of a list is double-clicked or a menu item is selected. Ex: Button click, The ActionListener interface is used for receiving the action events. 2.MouseEvent: MouseEvent is generated when a source such a mouse is moved, dragged,clicked,pressed or released Mouse Events are:Mouse_Clicked,Mouse_Dragged,Mouse_Pressed,Mouse_Released Mouse_Entered,Mouse_Exited etc. 3.ItemEvent: ItemEvent is generated when a source check-box or list item is clicked There are two types of item events which are identified by two integer constants: DESELECTED The user deselected an item. SELECTED The user selected an item. 4:KeyEvent: KeyEvent is generated when a source such as a key on the keyboard is pressed,typed These key events are following KEY_PRESSED KEY_RELASED KEY_TYPED 5:WindowEvent: Window Event generated when a source such as window is activated, deactivated, opened or closed Window Events: WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_ DEACTIVATED, WINDOW_DEICONIFIED, WINDOW_ICONIFIED, WINDOW_OPENED Event listener interfaces The Event listener represent the interfaces responsible to handle events. All listeners are interfaces from java.awt.event package. 1. ActionListener Interface: The ActionListener is notified whenever you click on the button or menu item. It is notified against ActionEvent. It has only one method: actionPerformed(). actionPerformed() method The actionPerformed() method is invoked automatically whenever you click on the registered component. Ex: public void actionPerformed(ActionEvent e) { //Write the code here } 2.MouseListener Interface MouseListener is notified when mouse is clicked ,pressed,entered and released. It is notified against MouseEvents. Mouse Events: mouse clicked ,mouse pressed,mouse entered ,mouse exited,and mouse released. Methods: 1.public abstract void mouseClicked(MouseEvent e); Invoked when the mouse button has been clicked on a component. 2.public abstract void mouseEntered(MouseEvent e); Invoked when the mouse enters a component. 3.public abstract void mouseExited(MouseEvent e); Invoked when the mouse exits a component. 4.public abstract void mousePressed(MouseEvent e); Invoked when a mouse button has been pressed on a component. 5.public abstract void mouseReleased(MouseEvent e); Invoked when a mouse button has been released on a component. 3.WindowListener:WindowListener is notified whenever you change the state of window. For ex:when you closed the window or opened the window WindowListener methods:. 1.public abstract void windowActivated(WindowEvent e); Invoked when the Window is set to be the active Window. 2. public abstract void windowClosed(WindowEvent e); Invoked when the user attempts to close the window. 3. public abstract void windowDeactivated(WindowEvent e); Invoked when a Window is no longer the active Window. 4. public abstract void windowDeiconified(WindowEvent e); Invoked when a window is changed from a minimized to a normal state. 5. public abstract void windowIconified(WindowEvent e) Invoked when a window is changed from a normal to a minimized 6. public abstract void windowOpened(WindowEvent e) Invoked the first time a window is made visible. 4. ItemListener ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The It has only one method: itemStateChanged(). Ex: public abstract void itemStateChanged(ItemEvent e) 5. KeyListener The KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. Ex :when you type any character from the keyboard It has three methods. 1.public abstract void keyPressed(KeyEvent e) Invoked when a key on the keyboard is pressed 2.public abstract void keyReleased(KeyEvent e) Invoked when a key on the keyboard is released 3.public abstract void keyTyped(KeyEvent e) Invoked when a key on the keyboard is typed 6.MouseMotionListener Interface The MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two methods. Methods of MouseMotionListener interface 1.public abstract void mouseDragged(MouseEvent e) Invoked when you dragged the Mouse 1.public abstract void mouseMoved(MouseEvent e) Invoked when you moved the Mouse Handling Keyboard events with an Example Keyboard events in java are generated when a key is pressed, the key is typed and a key is released. The key Listener interface is handling keyboard events. Each of the key Event handling methods takes a keyEvent object is its arguments. A KeyEvent object contains information about the key event. The various methods available in the keyListener interface are as follows: void keyPressed(keyEvent e) The keyPressed ()method is used to call when a key is pressed. void keyTyped(keyEvent e) The keyTyped ()method is used to call when a key is typed. void KeyReleased(keyEvent e) The keyReleased()method is used to call when a key on the keyboard is released void getKeyChar(): This method returns the key name related to the key pressed or released int getKeyCode():This method returns an integer number which is the value of the key pressed by the user. Example To illustrate Key board Events Adapter Class: Def:Adapter class is an implementation class of listener interface which contains all methods implemented with empty body. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code. The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. To avoid this unnecessary code adapter classes are used for various listener interfaces The Following are the Adapter classes 1.WindowAdapter : The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty 2.MouseAdapter : The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty 3.KeyAdapter: The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty 4.MouseMotionAdapter: An abstract adapter class for receiving mouse motion events.All methods of these class are empty 5.MouseInputAdapter The adapter which receives mouse events and mouse motion events. The methods in this class are empty. This class is present in javax.swing package Handling mouse Events MouseEvent: The user may click, press ,drag and move a mouse while interacting with the application. The Mouse Events are Cliked, Dragged, Moved, Pressed and Exited etc. To handle the Mouse Events, MouseLisener and MouseMotionListener interfaces of java.event.awt package are used. MouseListener MouseListener is notified when mouse is clicked , pressed, entered and released. It is notified against MouseEvents. The MouseListener Interface has following methods. 1.void mouseClicked(MouseEvent e); Invoked when the mouse button has been clicked on a component. 2. void mouseEntered(MouseEvent e); Invoked when the mouse enters a component. 3. void mouseExited(MouseEvent e); Invoked when the mouse exits a component. 4. void mousePressed(MouseEvent e); Invoked when a mouse button has been pressed on a component. 5. void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. The MouseMotionListener The MouseMotionListener is notified whenever you move or drag mouse. Methods 1.void mouseDragged(MouseEvent e) Invoked when you dragged the Mouse 2.void mouseMoved(MouseEvent e) Invoked when you moved the Mouse. Ex to illustrate Mouse Handling import java.awt.*; import javax.swing.*; class MouseEventEx extends JFrame implements MouseListener { JFrame jf, JLabel msg; MouseEventEx() { jf = new JFrame("Mouse Tracking"); msg = new JLabel("Mouse Events"); jf.addMouseListener(this); msg.setFont(myFont); msg.setHorizontalAlignment(JLabel.CENTER); jf.add(msg); jf.setSize(500, 500); jf.setVisible(true); } public void mouseEntered(MouseEvent arg0) { msg.setText("Mouse Entered"); } public void mouseExited(MouseEvent arg0) { msg.setText("Mouse Exited"); } public void mousePressed(MouseEvent arg0) { msg.setText("Mouse Pressed"); } public void mouseReleased(MouseEvent arg0) { msg.setText("Mouse Released"); } } Inner classes Inner Class:The class defined inside another class or interface is called inner class. In Java, an inner class is also known as nested class ▪ We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.It increases encapsulation. ▪ It can access all the members (data members and methods) of outer class including private. ▪ It requires less code to write. Syntax: class OuterClass { //code class InnerClass { //code } } Types of Nested classes(Inner) There are two types of nested classes 1 non-static nested classes (The non-static nested classes are also known as inner classes.) 2.static nested classes. Non-static nested class (inner class) i.Member inner class ii.Anonymous inner class iii. Local inner class 2.Static nested class i.Member inner class: A class that is created inside a class but outside a method is called member inner class. It is also known as a regular inner class. It can be declared with access modifiers like public, default, private, and protected. Syntax: class OuterClass { Outer class code; class InnerClass { Inner class code; } } ii. Local inner class A class defined inside a method is called local inner class in java. Local Inner Classes are the inner classes that are defined inside a block If you want to invoke the methods of local inner class, you must instantiate this class inside the method. Rules: ▪ Local Inner class cannot be accessed from outside method ▪ We cannot create object of local inner class inside the main of the outerclass. ▪ We should create object inside the function in which it is defined to invoke the methods of local inner class ▪ we can’t use private, public, or protected access modifiers with it. The only allowed modifiers are abstract or final. Syntax: class outer { void method() { class inner { code; } } // method } // outer public class LocalInnerEx Ex to illustrate LocalInner class { private int data=30; void display() { class Local{ void msg(){System.out.println(data);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ LocalInnerEx obj=new LocalInnerEx(); obj.display(); } } output: D:\apple\AWT>java LocalInnerEx :30 iii.Anonymous inner class Anonymous inner class is an inner class with out a name and for which only a single object is created. It should be used if you have to override a method of class or interface. ▪ An Anonymous inner class can declare by the use of a new keyword. ▪ The Anonymous inner class is used when you want to use any class only once. ▪ Anonymous Inner classes are very useful in writing implementation classes for Listener interfaces in GUI Programming. ▪ it is not possible to define a constructor for an anonymous class. Its name is decided by the java compiler. ▪ Anonymous inner class can be created by two ways: 1.class (may be abstract or concrete). 2.Interface syntax: Anonymous Inner class where the class can be an abstract class or a concrete class or interface. class t = new class() { public void method() { Code; } }; Ex to Create an anonymous class by use of abstract class abstract class Person { abstract void eat(); } class TestAnonymousInner{ public static void main(String args[]){ Person p=new Person(){ void eat() { System.out.println("nice fruits");} }; p.eat(); } } D:\apple\AWT>java TestAnonymousInner nice fruits 2. Ex to Create an anonymous inner class by use of Interface interface Eatable{ void eat(); } class TestAnnonymousInner{ public static void main(String args[]){ Eatable e=new Eatable(){ public void eat() { System.out.println("nice fruits");} }; e.eat(); } } D:\apple\AWT>java TestAnnonymousInner nice fruits Ex: write a java program to close a Frame using anonymous inner class import java.awt.*; import java.awt.event.*; class MyFrame extends Frame { public static void main(String args[]) { MyFrame f=new MyFrame(); f.setTitle("Anonymous Inner class"); f.setSize(300,300); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } 2.Static Inner class A static class created inside a class is called static inner class.We use the keyword static to make our inner class static. It can be accessed by outer class name. Static inner class can have static members as well as non static members Static inner class can access static data members of outer class including private. Static innerclass cannot access non-static data members or non static method. Syntax: class outer { code; static class Inner { code; } } Applet An applet is a special java program that can be embedded in the web page to generate dynamic content. It runs inside the web browser and works at client side. Applets are used to make the website more dynamic. To create an applet, a class must class extends java.applet.Applet class. An applet can perform many functions such as graphics, play sound, animation, arithmetic operations, play games etc. Every Applet application must import two packages - java.awt and java.applet. An applet is embedded in an HTML page using the APPLET tag and hosted on a web server. Advantages ▪ They are very secure. ▪ It works at client side so less response time. ▪ Applets can be executed by browsers running under different platforms. Uses of APPLET or Applications ▪ Applets are used for creating animation and games where the images can be displayed. ▪ Applets are used for creating dynamic web pages ▪ It is useful to play audio or music in Applets ▪ Displaying documents Disadvantage ▪ One disadvantage of Applets is that plugins are required at the client browser for executing applets. Explain the Life cycle of applet? 1.public void init(): is used to initialized the Applet. It is invoked only once. ForEx:We can initialize variables,creating components in this method. 2.public void start(): This method is called after the init() method ,if the user maximizes the web page. It is used to start the Applet. Ex: Any calculations or processing of data should be done and results also displayed 3.public void stop(): This method is called when Applet is to be stopped.If the user minimizes the webpage. 4.public void destroy(): This method is called when the applet is being terminated from memory.This method always be called before stop() EX:The code related to releasing the Memory allocated to applet. 5. paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like circle, square Applet Life cycle There are two standard ways in which you can run an applet : 1.Using a Java-Enabled Web Browser (By html file.) Applets are executed by a program called applet engine which is similar to virtual machine that exists inside the web browser at client side. ▪ If you are trying to execute your Applet in web browser ▪ first you need to compile your Java Applet program. ▪ create a separate HTML file and add the applet code in the html file by using tag Syntax: ▪ Now you can click the HTML file to launch the applet in the browser. Step1 : create the applet program with name First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet{ public void paint(Graphics g){ g.drawString(“Hello World",150,150); } } Step2: compile the java applet javac First.java Step3: create an html file and place the applet code in html file First.html Step4: Open the html file in browser you will get the output 2.Using appletViewer ▪ Applet are executed by appletViewer Standard tool. An appletViewer executes your applet in a window. ▪ This is the easiest way to run an applet ▪ To execute HelloWorld Applet with an appletViewer tool, you may also execute the HTML file ▪ HTML file is saved with ▪ RunHelloWorld.html First compile the Applet D:/kiran>javac HelloWorldApplet.java Run the Applet D:/ kiran>appletViewer RunHelloWorld.html You get following output: First applet program displaying msg (Executing applet through appletviewer tool) Step1. Create java applet program MyApplet.java import java.applet.applet; import java.awt.*; public class MyApplet extends Applet { public void paint(Graphics g){ g.drawString("welcome II CSE-D",150,150); } } Step2: compile the MyApplet D:/kiran> javac MyApplet.java Step3: create a html file with name myapplet.html and embedded java applet in html program myapplet.html step4: run the applet through appletViewer tool D:\kiran> appletViewer myapplet.html step5: you get output Passing Parameters to Applet Parameters specify extra information that can be passed to an applet from the HTML page. Parameters are specified using the HTML’s param tag. We can get any information from the HTML file as a parameter to the Applet Program. The tag is a sub tag of the tag. The tag contains two attributes: name and value which are used to specify the name of the parameter and the value of the parameter respectively Syntax: Ex: