You are on page 1of 199
AT 2 uu Per re i} a he Boda earl) | neva Ae As per Revised Syllabus of MSBTE - I SCHEME fidvanced Java Programming for Online Examination T. ¥. Diploma (Semester - V) Computer Engineering / IT Program Group (CO/CM/IF/CW) Mrs. Anuradha A, Puntambekar ME. (Computer) Formerly Assistant Professor in PES. Modem College of Engineering, Pune Mrs. Manjula V. Athani MTech. (Software System) (HOD) Deptt. of Computer Engineering Pravin Patil College of Diplomo Engineering and Technology, Thane =" TECHNICAL PUBLICATIONS \Wensie = wn tecnnicalubicatons orp ‘An Up-Tarust for Knowledge ga htps/ or iacebook.com/technicapublicatons wa €idvanced Java Programming for Online Examination TY. Diploma (Semester - V) Computer Engineering / IT Program Group (CO/CMVIF/CW) FintEdbon:Jne 2019 © Copyright with Authors Al publishing rights (printed and ebook version) rese-ved with Technical Publications. Ne part of this book should be reproduced in any form, Electronic, Mechanical, Photocopy oF any information storage and retrieval sslem withou! prior permission in wrting, kom Technical Publications, Pune. Published bys TECHNICAL 2°.°°80%).97525). PUGUGRTIGNS, cn: sesoetoviedstee Printer Yasin Prt 8 Bnd SiR. tou, hind Fae, Need Vilage Rod Ted, Bot Rune 411081 Price :€ 160 ISBN 978-93-89180-14-4 Il hl MseTE I PREFACE ‘The importance of Advanced Java Programming is well known in various engineering fields, Overwhelming response to our books on various subjects inspired us to write this book. The book is structured to cover the key aspects of the subject Advanced Java Programming ‘The book uses plain, lucid language to explain fundamentals of this subject The hook provides logical method of explaining various complicated concepts and stepwise methods to explain the important topics. Each chapter is well supported with necessary illustrations. practical examples and solved problems. All chapters in this book are arranged in a proper sequence that permits each topic to build upon earlier studies. All care has been taken to make students comfortable in understanding the basic concepts of this subject. Representative questions have been added at the end of each section to help the students in picking important points from that section. The book not only covers the entire scope of the subject but explains the philosophy of the subject. This makes the understanding of this subject more clear and makes it more interesting, The book will be very useful not only to the students but also to the subject teachers. The students have to omit nothing and possibly have to cover nothing more. We wish to express our profound thanks to all those who helped in making this book a reality. Much needed moral support and encouragement Is provided on numerous occasions by our whole family. We wish to thank the Publisher and the entite team of Technical Publications who have taken immense pain to get this book in time with quality printing Any suggestion for the improvement of the book will be acknowledged and well appreciated. Authors A.A. Puntambelar Manijta D. Athant Dedicated to God. SYLLABUS Advanced Java Programming (22517) Teaching Schome] _ Credit Eawitaati Shes error Theory Practical ulrle Peper] ese | PA | tom | ese pa | Total ie wax win | wax | win | wax] win | wax | win | wae | in | max | win 2 [1 fe | @ _foomm|roa] 2 | ao | o | 100] 40 | 2m | vo | oe | v0 | oo | 20 Unit Unit Outcomes (UOs) Topics and Sub -topics (i cognitive domain) Unit=1 | ta, Develop Graphical User] 11 Component, container, window, frame, Interiace (CUD programs using | pane, Abstract componente, he he | 39 ieee WT aomponens for 188 12 Creating windowed programs and Toolkit (AWT) applets 1b, Create Frame window with the | 7.3 AWT controls and layout managers : us ‘specified AWT components. of AWT controls labels, buttons, Ic, Arrange the GUI components | checkbox, checkbox. group, scroll bars, wsing’ epeciied layout | txt fild, text aren smaniger La Use of layout _ managers < flowLayout, Id. Develop a program using | ——_erdorLayout, gridlayout, cardlayout, ment and Dialog Boxes for the | gridbagiayent, menubars menus, dinlog given problem. boxes, fle dilog Unit- | 2a, Dilforentiate betwaen AWT and] 21 Introduction to swing : Swing features, Swring on the given agpect: Diflerence between AWT and Suing Swings : 2%. Develop Graphical user | 2.2. Swing Components : J4pplet, Icons ant interiace (GUI) programs using | Labels, Text Fields, Combo Boxes swing — for the] 23 Butions : The JBution, Check Boxes, ven problem. Radio Buttons. 2c, Use the given type of button in | 94 advanced Swing Components : Tabbed Java based GUL Panes, Scroll Panes, Trees, Tables, 24. Develop Graphical user | —_ Progress bar. tooltips Interiace (GUD programs using | 9.5 MVC Architectare Ravonced sing components | 22 ME tee for the given problem, Unit Use delegation event model to] 3.1 The delegation Event Model» Event develop event driven program | — sources, Event listeners een Nanci for the given problem. 3.2 Event classes : The Action Event class, Sb. Use relevant AWT/ swing] the Item Event chs, the Key. Event components) 10 handle the | class, the Mouse Event class, the Text given event Event class the Window Event class Se Use Adapter clases in Java] 33 Adapter clases program to solve. the" given weaases, peti 35. Bret lberer ere + Aptis Si Use ier clases ix_jva| 9° Bent tee nese «Aine programm to solve the given | Tisener’ Interface, Mouse istener problem. Interface, MouseMotion Interface, Tesilistener Inerace, WindowsListenet Interface Unit-1W | da, Use inetAddross class to know | 1 Socket Overview Client/Server, the IP address of the given | Reserved Sockets, roxy Servers, Nayworking host name Internet Addressing 46, Use URLConnaction classes to] 42 Java and the Net : The Networking read and write data tothe | Class and interiaces specified resource referred bY | 4.3 inetAdrose : Factory Methods, Instance the given URL. Nome oy Mena 4c Boeke pemee fee tant 44° TCP/IP Client Sockets : Whois TCP/IP Server sockets for the | 45. URL: Format, The URI Class given problem 46 URLConnection : TCP/IP Server Sockets 4d. Write program to ilustate the | 4.7 Datagrams : Dalageam Packet, Datagram Client/Server communication | Server and Client using datagiam protocol for the piven problem unit-v— | 5a, Choose SBC or ODBC] 5.1 Introduction to JDBC, ODAC. sng wit depending on the given | 52 JDBC Architecture : Two ter end three Intreting wth | appiaion sequent 8 eae ns we Henan tebese | 5. Explain function of the alven | 5.3 types of DBC Drive vier f JDBC. architecture fo tho fer/three her mecle, “| 84 Dever Interfaces and Driver Manager 4 class + Connection InteracenStainent Se Use relevent type of JDBC Interface, Prepared Statement Interface, Driver for the specified | leyess, fechas environment 55 The essential JDBC Program Sd. Elaborate. steps with example i TORE Pas to establish connectivity with the specified database. Unit- Vi Servlets 6a, 6, 6 Explain function of the given method of Servlet life cycle Use relevant Generic serviet to develop given web based application. Use relevant HTTP servlet to develop specified web based application. Develop servlet for cookies and session tracking to implement the given problem. 61 62 63 64 65 The Life Cycle of a Servlet. Creating simple Servlet: The Servlet API, javaxservlet Package, Servet Interface, ServletConfig Interlace, ServletContent Interface. ServletRequest Interface, ServletResponse Interlace, GenericServiet Chass The javaxservlethtip Package HiipServletRequest Interface, HupservioiResponse Intertace HitpSession Interface, Cookie Class, HipServlet_ Class, “HtspSessionvent Class, HlipSessionBindinygEvent Class Handling HTTP Requests and Responses Handling HIP GET RequestsHandling HTTP POST Requests Cookies and Session Tracking TABLE OF CONTENTS Chapter-1 Abstract Windowing Toolkit, (1-4) t0 (1-34) LA Whatis Abstract Windowing Toolkit (AWT) ? 1 = 1 1.2 Component, Container, Window, Frame, Panel 1 = 1 13 AWT Conttols.. os cscececce ped 13.1 Labels 13 2 Buttons 14 3 Checkbox 1-6 134 Checkbox Group 1 13S. Seroltbars Let ToxtFicld 1.8 TestAres 1-9 138 L 1-10 1.3.9 Adding Control on Applet Window... 1 © 11 1.4 Layout Manager 13 1.4.1 Flow Layeut 1b 1.42 Border Layout 1 143. GridLayout 17 144 CardLayout y-19 145. GridBaglayout 1-23 1.8 Menubars and Menus 1.6 Dialog Boxes, 16.1 File Dialog 1-29 Multiple Choice Questions with Answers... Lisi aeons Chapter-2 Swings (2-1) to (2-30) 2.1 Introduction to Swing 2-1 21.1 Swing Features 2-1 2.2 Swing Components JRrame. JApplet Icons and Labels Tentfield 5 Combo Boxes Buttons 23:1 Muon 23.2. Checkbox 23.3 Radio Button 24 Advanced Swing Component 24.1. Tabbed Panes 2.4.2. Seroll Pane 243. Trees 244 Tables 245. Progress Bar 24.6 ToolTips 25 MVC Architecture Multiple Choi Lip taeae tte Questions with Answers ....+4.2-25 Chapter-3 Event Handling (3-1) to (3 - 18) 34 The Delegation Event Mode! 3.1.1 Example : Handing Button Click 3.1.2. Event Sources 3.13. Bvent Listeners 32 Event Classes. 3211 ActionEvent Clas. 3.2.2 temEvent Cl KeyEvent Class Mouse vent Class TextEvent Class ou) 33. Programming Examples of Handling Events . 3-6 34 Adapter Classes 3-10 35 Inner Classes 35.1 Statie Membor Classes 3.5.2 Member Cla 3.53. Local Clases 3.54 Anonymous Classes 3-12 EventListener Interfaces 3-12 36.1. ActionListener Interiace 3-13 362. HemmListener Interface 5 3.6.3 KeyListener Interfuce 3.6.4 MouseListener Interface 36.5 MouseMetion Interface 366. TeatListener Interface 36.7 Window istener Interface 3-13 Multiple Choice Questions with Answers. ...... 3-16 Chapter-4 Networking Basics (4-1) to (4-34) AA Socket Overview... cee eee 4 411 Clint Server . 4 4.1.2. Reserved Sockets 42 4.13 Proxy Servers 4-2 414 Internet Addressing 42° Java and Net 42.1 The Networking Classes and Interfaces ...4=4 43° InetAddress 45 43.1. Factory Methods 4s 4.2 Instance Methods 4-9 433 InetbAddress and InetGAddress 4-9 44° TCP, 1Pand UDP 4-9 45° TCPAP Client Sockevs -10 460 URI Ag 462 The URL Path ‘ 463 The URL Class 41 4.7 URLConnection 48° URIClss 49. TCPAP Server Sockets 4410 Datagrams 4.10.1 Datagram Packet 4.10.2 Datagram Server and Client Multiple Choice Ques . Chapter - 5 swith Answers . Interacting with Database (5-1) to (5-20) 5.1 Introduction to JDBC and ODBC 1 52 JDBC Architecture Two Tier Model Three Tier Model 3 How JDBC Werks?. 5.3. Types of JDBC Drivers. S4 Connectivity with Database. . SA.L_ Driver Interfaces 54.2. Driver Manager Class 54.3 Connection Interface 5-7 S44 Statement Imertace 3: 54.5. ResultSet Inverface seul The Essential JDBC Program Multiple Choice Questions with Answers « ate Chapter-6 Servlets (6-1) to (6 - 24) 6.1 Introduction to Servlets. 6-1 6.11 Advantages 6-2 62 The Life Cycle of Servlet 6-2 oo 64 6s 66 Servlet API ‘The javax servlet Package. 65.1. Interfaces 65.1.1 Servet Interface. 6.5.1.2 SerletCoatigInerace 65.1. SeretConten Intorfoce 65.1.4 SersletReuest Interfice 6.5.1. SeretResponse Interface 652 Classes... 6.5.2.1 GenerieServie Clas. The javax.servlet http Package 56.1. Interfaces. (6.1.1 HtpServletRequest Interface 6.6.1.2 HupSeevetResporse Interface 66.1.3 HpSession interface 6.62 Classes 66.2.1 Cookie Class. 6-10 6-10 6-10 6-10 66.22 HupServle Class 6-10 6.6.2.3 HpSessionBvent Class. on 66.2.4 HupSessionBindingEvent Class. ...6~ LI 6.7 Handling ITT? Requests and Response, ....6=11 68 Cookies ..... 6-16 68.1 Constructors and Methods 6-16 68.2. Example 6-17 69 Session Tracking... 6-19 ‘Multiple Choice Questions with Answers 6-22 ‘Advance Java Programming Laboratory (L- 1) to (L- 14) Solved Model Question Paper (S-1) to (S -20) UNIT - 1 Abstract Windowing Toolkit What Is Abstract Windowing Toolkit (AWT) ? ‘The AWT stands for Abstract Window Toolkit. The AWT package contains large number of classes which help to i components in the Java Program. clude various graphical The graphical components include text box, buttons, labels, radio buttons and so on. 7.2] Component, Container, Window, Frame, Panel ‘The AWT classes are arranged in hierarchical manner which is known as AWT Hierarchy. Refer Fig, 1.2.1 ‘Component Eaton J [Ganvas | [Checkbox] [ohoes | [Gontaner] [abe] ts] [Berar ] [rencomponent Pana] [Window Teariea) [Tease] [ae] eos Fig. 12.1 AWT hierarchy The hierarchy components classes are - © Component : This is the super class of all the graphical classes from which variety of graphical classes can be derived. Ithelps in displaying the graphical object on the sereen. It handles the mouse and keyboard events. © Container This is a graphical component derived from the component class. It is responsible for managing the layout and placement of graphical components in the container. © Window : The top level window without border and without the menu bar is created using the window class, It decides the layout of the window. © Panel : The panel class is derived from the container class. Itis just similar to window - without any border and without any menu bar, title bar. ay Advanced Java Programming 42 Abstract Windoring Toolkit © Frame : This is a top-level window with a border and menu bar. It supports the common window events such as window open, close, activate and Frame(String title) ‘This creates the new instance of frame which has some title deactivate. + Following table enlists various methods of Frame Review question se 1. Explain AWT hierarchy in detail Methods Description [Slaw contrts eee cee have io weaatie + There are various graphical components that can be | | Pesizable) placed on the frame. These components have the | | void seffitl(String Title) _ | Sets the title ofthe frame classes, These classes have the comesponding | | Joiq eigen widthint | Sets the width and height methods. height) of a frame + Weean place the AWT Controls on Frame window | [oo erway or applet window using add method. ering cee 5 pea + When we place the components on the frame we - asses RC Ee void stVisible(boolean | Set the frame visible or not. visible) + The commonly used layout is FlowLayout. The HlowLayout means the components in the frame will be placed from left to right in the same manner as they get added, * Various components that can be placed for designing user interface are ~ 1. Label 2. Buttons 3. Canvas 4. Scroll bars 5. Text components 6. Checkbox 7. Choices 8. Lists panels 9. Dialogs 10. Menubar + Let us discuss these components one by one, but before that let us understand how to create a frame ‘on which we can place the components. Croation of Framo + InJava, Frames a standard graphical window. + The frame can be displayed using the Frame class. © The frame drawn using this class has standard minimize, maximize and close buttons. © The syntax of frame class is ~ 1) Frame() ‘This creates the new instance of frame which is Different Ways to Create Frames - ‘There are two ways to create the frames in AWT and these are - Extending frame cass Using instance oF ‘ame class Fig. 1.3.1 Ex. 13.1 : Create a java frame by extending the Frame class. Sol.: Java Program import java awt * class FrameDemo extends Frame 4 ‘public static void main(Stzingl] ange) { FrameDeme fr=now FrameDemo(); fretSize( 300,900) fraetVivible(teue); y Absanced Java Progremming Abstract Windowing Toctit Note that the initially the frame will not be visible. Hence we need to set the visibility ofthe frame. Ex. 1.3.2: Create a java frame by using an instance of Frame class, Sol.: Java Program laaport java.awr*; class FrameDemo! { public static void main(Stzingl] args) {rsetSize(900,000); servisible(enue); + } Output will be the same frame as above. [aa taboe Labels are simple components that are used to represent a single line read only text, User cannot change this text. Syntax The syntax of this control is Label (String s) Laabel(String s, int style) where the » of String type represent the string contained by the label similarly in the other label function style is a constant used for the style of label. It can be Label. LEFT, Label RIGHT and Label CENTER. Here isa JAVA program which makes use Label. ¥ Tectrial bltons An up tht naotedge Advanced Jae Programming tea Abstnct Windraing Toolkit Ex. 13.3: Write a simple Java program to demonstrate the use of label components Sol: Java Program[Use_Label.java] smnport java.aw*; class Use_Label { Frame fr-nevy Frame("This Program is for Displaying the Labe!"), tr setSize(400,200), fr.setLayout(new FlowLayout()); Serilng the Frame window Size fi.setVieible(true); Label Lt =new Labell'0X) Lebel L2=new Labell*CANCEL'); + Creating a two Labels trada(tt); frada\L2} + Adding two Labels on Frame 3 Window } (Open the command prompt and type the following command to get the output - C:\javac Use label java (C:\Java Use_label [3.2] Buttons Buttons are sometimes called as push buttons. This component contains a label and when it is pressed it generates an event. The syntax of this control Ratton (String 8} Java Program import java aut" class Use Button { public static void main(String|] args) ( Frame fr: jew Frame((This Program is for Displaying the Button"); fr stSiz(400,200), frsotLayout{now FlowLayout)} Abdnced Jaca Progaming Abstract Winwowing Tolkit fr setVisible(true}: Button B1=new Buston(’O%), Button Bnew Button("CANCEL'), fradd(B1); frade(R2); } Ei hn oe ee ‘We can create an array of buttons. Following is a simple Java program which illustrates this idea - Jaya Program[Use_Button_Arr java] import java.awt.*; class Use_Button_Arr { ‘public static void main(String|] args) ‘ int is Frame fr=new Frame("This Program is for Displaying the Buttons"); {tr setSize(400,200); ‘fesotLayout(now FlowLayouti)); frsetVisible(trae); Button buttons||=new ButtoalSh, String Fruitol|= {!Mango!"Orango', ‘Banana’ "Apple' Strawhonry'}: Bit +) 4 sw Button(""+Froiteli}; ‘trada(buttonsit) } y [El Ths Program is for Duplayng toe Buttons Mango} Orange] Banana] _Appie | _Sirawoem Testes! Pubiestons” An ap ft frinowledge Adoonced ova Prograraminy. 1-6 Abstract Windowing Telit Checkbox + Checkbox is basically a small box which can be ticked or not ticked. + InJava we can select particular item using checkbox control. + This control appears as small box along with label. The label tells us the name of the item to be selected. + The syntax of checkbox is as given below Checkbox(String label) where label denotes the label associated with each checkbox. + To get the state of the checkbox the getState() method can be used. Java Program|Use_ChkBox java] import java.aws.*; class Use_ChkBox: q public static void main(String|] argo) Bf int Frame fr=new Frame((This Program is for Displaying the Checkbox): fr.setSize( 350,200); fr setLeyout(now FlewLeyout(); fisetVisible(imueh, Checkbox box! =new Checkbox("Candy") Checkbox hox2=new Checkboxt'Ice-cream’); Checkbox hox’3=new Checkbox!"Juice"); fradd(bext); fadd(bvox2); face(vox3y; y Output [ET Program ifr Deplnying the Checibox = aa F candy T tce-cream I Juice T Technica Pubteatans” An yp tras bv aronieage Aeneed jaa Programming 4-7 7.3.4] Checkbox Group Abstract Windewing Toctkit The Checkbox Group component allows the user to make one and only one selection at a time. + These checkbox groups is also called as radio buttons, The syntax for using checkbox groups is ~ Checkbox|String str CheckboxGroup cbg , Boolean val), + Following isa simple Java program which makes use of this control Java Program[Use_CheckBoxGr java] import java.awt.” class Use_CheckSoxGr { public static void main(Stxingl] args) { Frame Fr = new Frame|"This program uses checkbox groups’ Er setl ayoutinew FlowLayout()}: Fr setSiza(300,300), FrsotVisiblo(tme); ChockboxGroup cbg—new CheckboxGroup|): ‘Checkbox box! =new Checkbox('Candy',cbg.true}; Fraddtbor!); Fradd(box2); Fradd(box’); ‘Output (ieyponeeiel Le kay © canay Cesram © 2uce 735] Scrotibars + Scrollbar can be represented by the slider widgets. + There are two styles of scroll bars - Horizontal seroll bar and vertical scroll bar. «Following program shows the use of this component. ‘Testrioal Pubestons An ue ra fornanlage Addoonced Jae Programing 18 Abstract Windowing Toolkit Java Program import java.awt.* lass Use ScrollBare { ppablic static void main(Stringi] args) £ Frame Fr = new Frame("This program has a scrollbars"); Scrollnar HSelector = new Scrollbar(Scrolbar HORIZONTAL); Scrolibar VSelector = new Serolibar(Scrollbar. VERTICAL): Br.setLayout(new FlowLayout()) Fr.setSize(300,300), FrsetVisible(tnie); Fradd(HSelector); Friadd(VSolector): Output La) This program has a scrollbars | = | G) | 83 ied jextField + The TextField is a slot in which one line text can be entered. In the TextField we can enter the string, modify it, copy, cut or paste it. The syntax for the text field is int TextFieldtint n) where n is total number of characters in the string, - Testis! Puateaions” An uo hat orkoowledioe Aatooncod ave Progremoning 1-9 Abstract Windoring Toolkit Java Program[Use_TxtFid java] smport java awt.*: clase Uso TxtFid ( public static void main(String{] args) { wnt: Frame fr=new Frame("This Program is for Displaying the TextField"): fr sor$i20(969,300); fe setLavout{new FlowbayoutQ) fesetVisible(teue); babel Lt =new Label(Enter your name here’), ‘TextField input =new TextFiela(20} fradaila): feadalinpett); Enteryourname here [Part] Textarea + The TextArea control is used to handle multi-line text. The syntax is ~ TextArea(int n,nt m) Where n is for number of lines and m is for number of characters. Java Program smport java. aw"; class Use_TxtArea 4 ppublio static void mein Stringl| arge) Testa Pusioatons An ue tnt fries Adoanced ova Programming 1-10 Abstract Windowwing Tootit 4 int i: Frame fnew Prane("This Program is for Displaying the Textarea’); trsetsize(350.300), fr.setLayout(new FlowLayaut()); fi. setVisible(tive); ‘Label L1=new Label(Enter your address here"); ‘TextArea input! =new Text Area( 10,20): fradd(Lt), sradatinputty; } + ‘output wySweet Home No 101, Shivaj Road, Gandhi Chom lPune| Enter your adaress nere + Listis a collection of many items. + By double clicking the desired control - m we can select it, Following Java program makes use of this Java Program[Use_List java] import java.awt.; class Use List t public static void main(String[| arge) { int: Frame fr=new Frame("This Program is for Displaying the List fr.setSizo(50,900), fu setLayout(new FlowLayout(); IrsetVisible(tme); List flower now List(4,falee); - Tearne! Pubtcstors An pint oraronteege Adownced Java Progrannning Ln Abstract Windowng Toolkit ‘lower.add(‘Rose"); flower. add('Jasmine'); Alowor.add('Lotue'); Aower.add(Lily'); freda(tovrer); Output [Bj This Program is for Displaying the List (=a Rose Jasmine En uly NS ~, 733] Adding Control on Applet Window ‘Applets are the small Java programs that can be used in internetworking environment. © These programs can be transferred over the intemet from one computer to another and can be displayed on various web browsers + We can add control on Applet window. For that matter let us first understand how to create an applet Stop 1 : Creation of Applet| ‘+ Normally the applet code makes use of two classes - Applet and Graphics. ‘+ For the applet class the package java.applet is required. This class provides the applets life cycle method such as init(), start) and_ paint). + The Graphics class is supported by the package java.awt. © Here isa simple applet. Java Program[First@pplet.java] te This is my First Applet program “" import java.awt.*; = TeshnealPubtestors™ - An uo ht or nowlece Adeanced Jaca Programming Ln Abstract Windoring Toolkit Import java.applot.* Public class FisstApplet extends Applet ¢ public void paint(Graphics g) { G.drawString(This 1s my First Applet’50,30), } } Program Explanation + In above given small applet program, the main intension is to display the message "This is my First Applet’. Let us start from the beginning of the program - +The first three lines represent a comment statement. + Then next comes import java.awt.*; ‘import java.appiet.*; We always need these two packages to be imported in the program, The java.awt package consists of java awt classes. Here awt stands for abstract window toolkit, ‘The AWT provides the support for window based graphical interface such as for drawing. screen, windows, buttons, text boxes, menus and so on. The other imported package is javaapplet. This is essential because we need to use Applet class in our applet program which is included in java.applet package. + The functionalities that are required to run applet the web browser supported by java.applet. inside are + Then comes public class Firstapplet extends Applet ‘The class FirstApplet is a subclass of class Applet. Hence the keyword extends is used. Java requires that your applet subclass (here it is FirstApplet) should be declared as public. Hence is the declaration! + We have then defined a method public void paint|Graphies g) ‘This method is used to paint something on the screen and it can be text, line, circle, rectangle or anything, Thus paint is a method which provides actual appearance on the screen, And this method requires a parameter to be passed as an object of class graphics. ‘Therefore an object g of class Graphics is passed. + Using this object the method drawString of Graphics class is invoked. [Note that Graphics class isa part of java.awt package) g.érawString("Thie ie my First Applot'60,20} ‘To method drawstring, firstly we have passed a string Which we want to get displayed, then 50 and 30 represents the position of the string on the screen ie. x and y positions respectively, ‘Step 2: Execution of Applet We can execute the applet using the Appletviewer tool. Following steps can be applied to run the applet using the Appletviewer. Step i) To run the applet without making use of web browser or using command prompt we need to modify the code little bit, This modification is as shown below ” ‘This is my First Applet program ” import ‘import java.applet* r ‘This will help to understand Java that the source program is an applet with the name FirstApplet. By at's this edition you can run your applet program merely by Appletviewer command. Step ii) DAtestjavae FixstApplet java D\test> Appietviewer FirstApplet java Techni Pubesions™ An upttr to bnaulecne Adtane ow Preranmmting Step 3: Adding Label Control on Applet “import java.awet ‘import java.applet."; r ” public close Us { public void init) { Labo] Li=new Label|'OK"); Label L2=new Label('CANCEL?; aaa); aaait2), » y For executing the above applet, open command Ige_Label’ width =350 height=200> Label extonde Applet prompt window and give following commands Java Use Label java Appletviewer Use_Label java ‘Output Applet OK CANCEL Applet siaried ‘Review Questions 1. Write a program in Jave using AWT to introduce fextfiold and textarea components 2. Explain carious types of buttons used in AWE. Write 1 Jon program to ltustrate ther nse. [Ea Layout manager Definition : * A Layout manager is an_ interface which automati lly arranges the controls on the screen. 8 Alstvaci Winding Totit + ‘Thus using layout manager the symmetric and systematic arrangement of the controls is possible. + Various layout manager are - 1, Flow layout 2.Border Layout 3. Grid Layout 4. Card Layout 5. Gridbag Layout Let us discuss these layout managers one by one. 141 Flow Layout + FlowLayout manager is the simplest Layout manager. * Using this Layout manager components arranged from top left camer lying down from left to right and top to bottom. are + Between each component there is some space left. + ‘The syntax of FlowLayout manager is as given below - FlowLayoutiint aligament) Where alignment denotes the alignment of the components on the applet windows. + ‘The alignment can be denoted as : FlowLayout LEFT FlowLayout RIGHT FlowLayout CENTER + Here is a Java program which makes use of seven checkboxes which are aligned on the applet window using FlowLayout manager, Java Program{Flowl Demo java] import java.awe.*; import java.applet.* P ‘ ” public class FlowLDemo extends Applet //Using Applet Window { string msg: Checkbox box1=new Checkbox(‘Sunday’); ‘Checkbox box2=new Checkbox(‘Monday’): (Checkbox box3=new Checkbox(‘Tuoaday’) Checkbox boxa=new Checkbox( Wednesday’) Chockbox box5=new Checkbox("Thursday"): (Checkbox box0=new Checkbox( Friday’); (Checkbox box/=new Checkbox('Saturday’}; public void initi) Teale Puaons -nup raat bv Imowiade Adtanced fase Programming ao Abstract Winding Tottt { TAZ] Border Layout /iereeting FlowLayout manager . ae etleo rel de ait edad tv In BorderLayout there are four components at the Hadling the compouscte with Left aligneat four sides and one component occupying large area adatbox!); at the centre. a + The central area is called CENTER and the ‘sadiecil components forming four sides are called Shapes), LEFT,RIGHT,TOP and BOTTOM. edabox6), + Following program consists of one big message , add(box7), stored in variable msg which is to be displayed at } the centre. And in the init method it shows that four ‘output sides are occupied by the Buttons. Java Program|Borderl Demo.java] aE Soro en arin" ‘Applet ] import java.avrt.t; > (Buriday! 7 Monday Tuesday I” Wednesday thursday Friday saturday Applet started, Program Explanation : In above program, 1) We have created an applet window. 2) Then Seven Checkbox controls are created each for the name of particular day. 3) Then using setLayout the layout manager Flow Layout is set. The following statement is used to set this layout manager setLayout(new FlowLayout(FlowLayout LEFT)}; Note that the controls are left aligned because of FlowLayout LEFT 4) On this applet window seven checkbox controls are placed using add method. import java.util"; fe < 4 public class BorderLDemo extends Applet 4 String meg="India is my country.\n'+"All Indians are my, brothers and sisters.\n'+ “Tlove my country and I am proud of its rich and varied heritage."+ ‘Tshall always strive to be worthy of it.\n'+ “shall give respect to my parents.teachers and elders and treat everyone with courtesy.\n'-+ “Tomy country, to my people, I pledge my devotion \n"+ “tn their well being and prosperity alone lies my happiness.\n"+ Jai Hind." public void init() q setLayout(new BorderLayout(); add(new Button(‘North"),BorderLayout. NORTH): ‘add(new Button('South’),BorderLayout SOUTH): add(new Button(‘East"),BorderLayout. BAST); add(new Button('West’),BorderLayout WEST); add(new TextAree(isq) BorderLayout. CENTER): y ) = Technical Pbieatons” An vs hast or nowedge Addsancd Joa Programming 1s Abstrsct Windoncing Pootit Program Explanation : In the above program, we have created object for BorderLayout manager using setLayoutinew BorderLayout() Then using BORDER NORTH BORDER SOUTH BORDER FAST BORDER WEST + The four sides are set with the help of Button control. The central large area is formed using TextArea control which is called as BORDER. CENTER +The concept of Border! ayout can then be clearly understood with the help of above given output. + In this Layout manager, we can add one more method called getinsets(). This method allows us to eave some space between underlying window on the applet and Layout manager + Weave used this method in the following program. The syntax of Insets method is Insets(int top int lftint bottom int sight) ‘The top Left.bottors and right parameters specify the amount of space to be left Java Program import java.applet.t: import java aut." import javacutil.*; p ‘ 7 public class Borderl.Deme extends Applet { ‘String msg="Indla is my country.\n'+"AllIndlans are my brothors and cisters.\n'+ “Clove my country and T am proud ofits rich and varied heritage." + shall always strive to be worthy of it \n'+ "T shall give kespect to my perents,teachers Teshnesl Fublestons An uth oriole Adeanced avs Prograraming 116 Abstract Windowing Toolkit and elders and treat everyone with courtesy.\n'+ “To my country, to my people, | pledge my devotion.\n'+ “In thelr well being and prosperity alone lies ‘my happiness \n'+ "Jai Hind’ public void init) 4 s0tBackground (Color green); setLayout{nevr BorderLayout(); adanew Button(North”) BorderLayout. NORTH): add(new Button(‘South") BorderLayout SOUTH); add (new Button(East’),BorderLeyout.SAST); add(new Butron( West’) BorderLayout WEST): add(now Text Area(msg),BordorLayout. CENTER); , public Insets qetinsets() q return new Insets(20,20,20,20); } 3 ‘Output indians are fry brotners and sisters, FNewve my county ana tam provid of sich and vari | shail give respect omy parents;teachers and elders and Weal 8 [ro my country, to my peorie, 1 pledae ry devoucr | tisk wall boing ana proeperty stone lies my happiness. ‘Anolet started. ‘This Space is left in between, Ex. 141: Writea Java program which erenie border layout and adds tivo text boxes to it. Sol, Borderl Demo java import java.applet.*; import java.awt.” impor java.util"; Aiteanced java Programming 17 i ‘ 'GridL.Domo" wridth=400 hoight=400> Tecnica Pbteaions An yp bras hnowedge Albsiract Windowing Pooh Aadounced aon Pregramnaing 1:18 E public class CridLDomo extonds Applot { int n=4,m=3; public votd init() { setLayout(new GridLayout(n.n)) forlint i=Oj1d ‘Applet ‘Applet stated [EEA caratayout + Sometimes we want to perform various sets of graphical controls at a time then CardLayout is used. + Thus CardLayout manager allows us to have more than one layouts on the applet. + The CardLayout is conceptually thought as a collection of cards lying on a panel. + Wenhave to follow following steps - Step 1: We have to create two objects 1. Panel object 2. CardLayout object Step 2: ‘Then we have to add the cards on the panel us panel obj setLayout(layout. obj); where panel_obj is an object of panel anf leyout_cbj is an object of CardLayout 1g add() method. For example - Step 3: Finally we have to add the object of panel to main applet, For example - add(panel_obj} These all stages seem to be complicated. Hence let us understand following program which implements CardLayout, Java Program|cardDemo java] //Tnie program domonstatos cardLayout [Phe dynamic selection of fruit/flower/colour can be made ae ‘Testa Fubleatons” anys trtfer knowlege Aateanced Java Programming 1-20 Abstract Wiradowing Tootkit /fasing cardlayout component import java.awt.*; import java.awt.event.*; import java.apples." n 4 public claes cardDemo extends Applet implements ‘ActionListener MouseListener 4 ‘Checkbox mango,apple,roze,otus,Red, Green; Panel panel_obi: CardLayout layout_obj: Button fruit fewer colour, ublic void inst) { fruit=new Button( Fruit) ‘ower=new Button(Fiowsr"); colour=new Button('Celour’) /adding the button controls atau) adalGovrer); edka{colour}: /tgetting object of Cardlayout layeut_obj=now CardLayout() /Igetting object of Panel panel_obj=nevr PanelO panol_obj.setLayoutilayout_objl; lading checkbox controls for fruits mango=new Gheckbex(‘Mango') apple =nevr Chockbex("Applo /Tadding checkbox controls for lowers rose=new Checkbox( Rose’) lotus =now Checkbox("Lotus') /Tacding checkbox controls for colors Red=new Checkhox("Red’) Groon=now Checkibox('Green') Panel fruit_pan=new Panel: frait_pan.add(mango); frait_pan.add(apple}; Panel flower_pan=new Panel(); Aower_pan.ada(rose), flower_pan adallotus): Panel colour_pan=new Panel() Pears ~ An utr ferkroniedge Advanced ace Pregramning 121 Abstract Windoeing Vootit ccolour_pan.ade(Red); colour _pan.ade(Creon); panel obi-adaait_panFrait); pnel_obj.ada(fower_pan’'Flower) ppanel_pbj ade(solour_pan “Coie ada(penel_ obi) JIrogicter tao components to event listener ‘nuit addActionListenorthis) flower addActionListener(this; colouradkiAetionListonorehis}; adaMouseListenenthis} + ‘ifliowing empty methods are nocessary for mouse vente pubhe void mousePressee(Mouse8vent m) { layout_objnext(panol_obj) > public void mouseClicked MouseB vert) { + public void mouseBntered(MouseEvent x) { + public void mouseBxited(MouseBvent m) { 3 public Yoid mouseReleased(MouseEent m) { + public void actionPerformed(ActionEvent ¢) { ile getSourcet)== rat { layout_ob.2hovr(panol_obj "Fru + clse ff. get Sourcet)==fower) { layout 9b) show{(panel_ob) Flower’) } lve iff. gotSoutco()~—colou) { layout obj.show (patel obj "Cclow") } fend foe actionPertcrmed method Hiend of class Tesiicl Puna” Anup tua bv nowtadge Alteanced Jona Progranoning 12 Abstract Window Toolkit Output(Run 1) “101 Applet Frat) Flower | Colour] mango [7 Apple Applet started. Output(Run 2) lox Applet [Fiat (Fiower| (Coiaue| rose Pilot) Applot started ‘Output (Run 3) ear Demo. lol ‘Applet Fruit] [Fiower| (Coiour) Ree WiGieerl Apalet started Program Explanation : «It is clear from the output that we can have a combination of various components lying on the same applet and can be invoked as per need. That mean if we click on Fruit button then we should get two checkboxes namely : Mango and Apple. #Ifwe click on Flower button then we should get two checkboxes namely : Rose and Lotus. Similarly, if we click on Colour button we should get two checkboxes namely : Red and Green. + Inabove program, we have used to event listener interfaces : ActionListener and MouseListener. + Wehave created panel object and Layout object. + In the init method we have first created and addled the Button controls. Then CardLayout on the pane s placed + The panel is then set for the applet window + Various components such as checkboxes and Buttons are added to the panel. + Inorder to understand mouse events some necessary empty methods are written. F Testa Publeaions An up tas rknowiedse Adoanced Jaen Programing 1-23 Abstract Windewing Tochit + In the actionPerformed() method, on the click of Fruit button, two corresponding check boxes are shown, Same is true for Flower and Colour buttons TAS] GridBagLayout + The GridBagLayout is the most flexible and complex layout manager. + The GridBagLayout manager places the components in rows and columns allowing the components to occupy multiple rows and columns, This is called display area. GridBagLayout performs three functions using values from the GridBagConstraints parameter in the add() method 1. Grid position, width and height describe the display area using gridx, gridy, Gridwidth and gridheight values, 2. Position within the display area using fill, ipadx and ipady. 3. Identifying rows and columns which receiveextra space on expansion using weightx. and weighty + The layout can be set as follows Container pane= frame getConientPane!); pane setLayout(new GridBagLayout(): + The component can be added as ‘pane.add(component,constraintObject}//pane is « container pane +The following values are then set - ©. grid and gridy : These values denote the integer column and row value of the component. o. gridwidth and gridheight : They denote the number of columns and rows the component occupies. © weightx and weighty : They denote the extra space occupied by the component horizontally or vertically when the output window is resized. (0 fill: The fill vatua denotas how the component should expand within tha display area. Typical values, GridBagConstraints. NONE // Can not expand (Default) GridBagConstiaints. VERTICAL // Expand vertically GridBagConstraints HORIZONTAL // Expand horizontally GriaBagConstraints.BOTH —_// Expand vertically and horizontally © ipadx and ipady : These values denote increase and decrease in horizontal or vertical preferred size of the component Default value i 0. Ex. L4.2: Write a Java program thet illustrates the use of GridBagLayout Sol. : Import java avr." impor java applet. p | MenuBar Menultem [4] CheckboxMenultem_ Q.38 Menu items are acided to a] menus [b|menuibar [c] frame [a] both a and b Q.39 Dialog box does not have minimize and rman ition [iliase a true Testnesl Pubiesions” Anus tint frinowiedse Abteanced Jaoa Programming 1 Abstract Winonsing Polit Q.40 A dialog box is referred to as modleless if the user does not have to close it in order to continue ‘using the application that owns the dialog box. true [P)false Q.41 The _ class displays a dialog window from which the user can select a file. [a] Dialog [b] FiteDiatog [a] None ofthese 1 |b[2 [ola fala le s. |elo jelz fafa |b 9. |p [10.)a|1.[a]i2[e 13. |a | 14. fe | 15. b | 16.|b 17. |¢ | 18. |b | 19. |b | 20.| a1. |b | 22.]a|23.|b|24.|d 25, |a |26.|b|27.|¢|2@/¢ 29. |a|30.d|a1.]¢| a2] 33, |d|34.] 4] 35.|b | 36. | 97. |a |38.|a|99.]a| 40] a a1, |b goa Technical Pubicaions" Anup fmt fo inode Swings 24 Introduction to Swing = Swing is another approach of graphical programming in Java. + Swing creates highly interactive GUL applications. + Itis the most flexible and robust approach. Zit ] swing Features 9 Swing has following two important features — 1. Pluggable Look and Fae! : ‘+ Swing support several look and feels. Currently it includes support for Windows 98 and LINIX Motif. Swing allows the user to switch look and feel at runtime without closing the current application. It is possible to create your own look and feel for ‘swing components. Lightweight Components : Most of the Swing components are lightweight ‘That _means using simple graphics primitive components can be created, With lightweight components, each component renders itself using the drawing primitives of the Graphics object ‘Adcitional Features 1. Swing contains wide variety of new components such as tables, trees, sliders, progress bars and so on. 2. Swing components can have tooltip placed over them, en 3. It is possible to bind the keyboard events with the components in Swing 4, There is a debugging support for rendering of created swing components Limitations of AWT Following are some limitations of AWT - 1. AWT supports limited number of GUI components 2. The components defined by the AWT are heavy weight components. 3. The behavior of AWT components varies when the container operating system changes, 4, The AWT components are developed by using the platform specific code, 5 The AWT component is converted by the native code of the operating system. 2.1.2 | Difference between AWT and Swing Sr.No. AWT Swing 1. The Abstract ‘The Swing is light Window ToolKit isa weight component heavy weight because it’s the ‘component because responsibility of VM every graphical unit to invoke the native will Invoke the native _ methods, methods, deans Jos Progonroning 22 Swings ‘The look and feel of AWT depends upon As Swing is based on Controller pattern, the look and feel of swing components in independent of hardware and the operating system. AWT occupies more Swing occupies Tess Swing is extension to AWT and many Azawhacks of AWT powerful than Swing, Review Questions 1. What is Swing ? Give features of Sting 2. Differentiate between AWT and Swing 3, What are limitations AWT ? 2.2 ] Swing Components + In order to display any JComponent on the GUL, it is necessary to add this component to the container first + If you do not add these components to container then it will not be displayed on the GUL + The swing class component hierarchy is as shown by following Fig. 2.2.1 + There are two important features of swing components ~ Firstly, all the component classes begin with the letter J and secondly all these GUI components are descendant of JComponent class. Let us now learn how to place these components on the GUL beet] belongs to java. tana. Cb f Comparent | belongs to java. awt. Cormpenent { Cantarer |] belongs te java, awt Container f ~eompenent] belongs to javax. svang. JComponent | ____,_, [Feemecear] [ratte] [amos] [Dsiee — — Trews] [tenth Fig. 2.2.1 Swing class component hierarchy Toohniva Publestons” =n yp frat roads Afvonced faa Programming 2-3 BE ee In Java, Frame is a standard graphical window. ‘The frame can be displayed using the Frame class. ‘The frame drawn using this class has standard minimize, maximize and close buttons. ‘The syntax of frame class is - ‘) Framet) This creates the new instance of frame which is invisible initially. fi) Framo(String title) ‘This creates the new instance of frame which has some title + Following table enlists various methods of Frame lass Methods Description void setResivablejboolean Sets frame to resizable resizable) void setTitle(String Title) __ Sets the title ofthe frame void setSize(int widthyint Sets the ividth and height eight) ofa frame String getTitled (Obtains the tile of the frame void setVisible(boolean Set the frame visible or not visible) A frame can be created by two ways ~ + By extending the Frame class + By creating an instance of a Frame class. Ex. 221: lass. Sol. Create a java frame by extending the Frame Java Program import javaavet.*; class FrameDemo extends Frame { public static void main(String|] args) { FrameDemo fnew FrameDemol); f.setSize(300,300); Swings frsetVisible(tmue); ‘output [Note that initially the frame will not be visible. Hence ‘we need ta set the visibility of the frame. Ex. 222: Frame class. Sol.: Create a jave frame by using an instance of Java Program impor: java awe." clase FrameDemol 4 public static void main(String!l args) { Frame fr=new Frame(); ‘s0tSiz9(00,300); fr. setVisiblo(true); + d (Output will be the same frame as above, EEE] nore The JApplet is a fundamental swing class. extends the Applet class. ‘Thi Ie supports the pane It is much more powerful than the Applet class. Various panes are content pane, glass pane, and root pane. Tacs Pubcon” Anup tit forknonlcge Adoanced Jas Programming 2-4 + The add method can be used to add the content pane. + The add method of Container class can be used to add the components on the GUL + All the life cycle methods used (such 2s init paint) in Applet class can be used with JApplet. Jova Program[AppletDemo, import java.amt.*; Impor java awt event.” import javaxewing.*; va] "applet code= AppletDemo.class helght=300 widih=300>*/ public class AppletDemo extends JApplet: public void paint|Graphics g) { g.drawString(‘WELCOME TO SWING PROGRAM 20.40): + How to run Swing applet program ? (Open command prompt and type following command And following output can be obtained Output Li Applet Viewer Applet. — xX Applet WELCOME TO SWING PROGRAM Applet started, Adoanced av Programing 2 swings Ex. 223: Write a Swing program to display a smiley face Sol. import java.awt.t; Import java.awt event.*; ‘import javax.swing." {**/ public class smiley extends JApplet ‘ public void paint(Graphies ¢) { .orawovaK(20.40.250,250) gedrawOval(70,100 50,60); gedrarvOval(180,100,50,50); ‘crawwAre(100, 150,100, 00,180,180); , } ‘output Aoplet | Applet started. Program Explanation : In ebove program, (1) We have created a JApplet. This applet contains the paint method. The paint method is called to raw the output directly on the surface of the component. (2) Using the object of Graphics class we can invoke the methods drawOval, draw Are Testrial Publeatans Anup tt er knonladee Adon ow Prgrnming Seige + For getting the output of the above program | Java Program[ComboBoxProgavel following commands can be given on the command | “import javaewr.; prompt- import java wt overt“ F\SwingProg>javec TatslaProg java import javax suring F \SwingProg> ApplotViewor TetioldProg java r ‘The Applet Viewer will display the GUT as follows “pet cos ~ComsnBostog with bh output ye Program Explanation To place the textfield control on the GUI we have followed following steps - 1. Using the getContentPane method an object for the Container class is created. This object is taken in the variable contentPane 2. The Layout is set using the contentPane object by the statement contentPane.setLayout new FlowLayout(}s ‘The default layout is FlowLayout but you can set other layout managers such as GridLayout, BorderLayout and soon. 3. After setting the layout manager, the TextField component can be created and placed using add method. In above program, we have created tivo text fields, In the first text field, the string “Hello” is already written during its creation but the second text field is kept blank and some string can be written into it during the execution, [225] combo Boxes + JList and JCombobox are very similar components but the JList allows to select multiple selections whereas the JCombobox allows only one selection at atime. + A combo box is a combination of text field and the drop down list. The JComboBox is a subclass of JComponent class. ubli¢ class ComboBox?r0g extends JApplet implements ItemListener { JLabel bs public votd init 4 Container contontPano=gotContontPano() contentPane.setLayout(new FlowLayeut()); IComboBox co=new JGomboBox(); co.addltemyappie’) o,additom‘orange"); co.additom("grapos"): co.addlltemListenes(this) contemPane.add(co), L=new JLabelinew Imagelcon(’apple git) contontPane.ada\(L. |; } public void itemStateChanged{TtemBvent e) { String str=(String}e.getitem); J/imvokes the appropriate image file LsetIcon(new Imagelcon(sir+” if); Output ‘An upthrsforknonadse Advanced ova Progranmming 29 Swings Imagetcon orange=new Imagetcon(‘orange cif} //Creating image icon ‘Button B2=naw JButton(orange); //associating image with button B2.s0tActionCommand(‘Orango'); B2.addActiont.istener(this};//button pressed event contentPane.ade(B2); Imageicon grapes=new lmagelcon("grapes gi), ‘JButton B3=new JBution(grapes); B3,setActionCommand( Grapes"); BS. addActionl.istener(this}: contentPane.ace( 2); ‘T=new JToxtField(20); contentPanc.ade\T};//placing the toxtfiold on the GUI } ‘public void ectionPerformed(ActionEvent e) { ‘T.serTex:(e.gorActienCommanc()), //retrieving the text associated with button, } For getting the output open the command-prompt and give the following commands ~ FASwingProg> javac ButtonProg java FASwingProg> AppletViewor ButtonProg java and you will get the applet as follows ~ ‘Output Ormge Applet starae Program Explanation The above program, is inherited from the JApplet class. In the init method, we have written the code 1. Create a container object by using the getContentPane method, This object is now in the variable contentPane. 2. A layout manager such as FlawLayout is used to set the layout of the GUL 3. The bution components are then placed on the GUI using the add method. = Tectia) Pubitons” An ye ia frmaniedoe Asoc foe Programe 2-0 4. These push buttons are associated with some images using ImagelCon class. To this Imagelcon class appropriate gif file is passed as an argument. Thus corresponding image gets associated with each corresponding push button. We have associated an ActionListener event with this program. This is necessary to handle the events when a push button gets pressed, We have associated some command string when the particular button is pressed. This can be done using setActionCommand method. The event handler can be invoked using the methods add ActionListener(this). When this a call to this method is given the control goes to the function actionPerfomed. In this method we are simply displaying the appropriate command string in the textbox Z| Checkbox + The Check Box is also implementation of AbstractButton class, But the immediate superclass JCheckBox is JToggleButton. +The |CheckBox supports two states true oF false. + We can associate an icon, string or the state with the checkboxes, The syntax for the Check Box will be = JICheckBoxitcon ic): IOheekBox{Icon ic, boolean state); IheekBox(String »); “ICheckBox(String s,hoolean state; ICheckBox(String s..con ic boolean state): + Following program illustrates the use of check box Java Program|CheckBoxProg,java] import java aww." import java.awtevent.*; import javax swring.* ie ” public clase ChockBoxProg extends JApplet implements ItemListoner { JTexField 7, Public void init() { Container contentPane=getContentPane(|; theckBexProg’ width=300 height=300> conten:Pane settayout(new FlowLayout()} \IheckBex chiel=new JCheckBax(‘Apale") chit addltemListener(this);// invoking the event handler conton:Pane.addchirt); ICheckBox chie2=new IChackten( Orange’) (chk2,additemListener (this); // invoking the event handler cconten:Pane.add (chk) ‘ICheckiBox chikd—now JCheckBox('Grapos" chk’ adaitomL.istonerithis); // invoking the event handler of TecrncalPuetoatons An ust er enoweoge Adoanced Ja Progranming 20 Suings contentPane.add(chk3); ‘T=new JTextField(5); contentPane.add(I); BurtonGroup bg= bbg.adalchiet) bg adalchiea), ButtonGroup helps the ba.ada(cnics): objects behave mutually yw ButtonGroup(); } public void itemStateChanged(ItemEvent e) { ICheckox chk=(JCheckBox)e.cetitem| ‘T.setTex(chk.getText())//displaying the appropriate string in textbox: Program Explanation In above program, the ItemListener event is implemented. Using the additemListener(this) method the event hendller function itemStateChanged is invoked. Thus on the clicking corresponding checkbox , the appropriate string will be displayed in the text field Radio Button + The RadioButton is a subclass of JToggleButton. This control is similar to the checkboxes. + The syntax for the Radio Box will be - JRactobutvondicon te; RadioButton (leon ic, boolean state): JRacioButton (String #); JRacioButton (String s,beclean state}; JRacioButton (String s,Icon \c,boolean state); + Following program illustrates the use of radio buttons, Java Program|RadioButProg java] import javacawt.t; impor: java.awtevent.*; impor javax.swing.* Testnia Fubleatons tn up tus rinowiedse Adoonced Joa Programing 22 fe 7 public class TabbedPaneDemo extends JApplet 4 fabbedPaneDemo' width~500 height=400> public void init() { JTabbodPano mytpano = now JTabbedPano|); Adding the folders on the mytpane.addTab(‘Laptop', new LaptopPanel()); tabbed pane mytpane.add'Tab(‘OS", new OSPanel)); mytpane.adaTab(‘Database”, new DatabasePanel()} mytpane.addTab(‘Lencuacies’, new LangPenel(): goiContontPano().adé(mytpane); } y ea clase LaptopPanol extonds JPanel Magy Simgpronent atin { public LeptopPanel() { “JRadioButton jebi = new JRadioButton( DEE adeeb ty RadioButton job2 = new JRadioBution(‘Samsung’), adairo2y RadioButton jeb3 = new JRadioButton("HP"); Teetnita Publestons” Anup fat rinedge Addoanced avs Programming 2-14 ‘acajib3); RadioButton jrb4 = new JRadioButron(“Acer): ‘addl(nbay; ButtonGroup by=new ButtonGroup\); bg adjbt); bg. adeljeh2); bg.adaleh3); be.adalb4); } , class OSFanol extends JPanel == OS Component defined | « public OSPanel0) ( SComboBox jeb = new JComboBox(): ich adaltom("Windows XP); job.addltom("Windowes Vista job.addltem(Windows 7} job.addllsem("Ubuntu’) edaljcb); } ¥ Database Component class DatabasePanel extends JPanel delined { public DatabasePanel{) ( ‘ICheckBox cbt = new JChockBox"Oraclo'); ‘adl(eb 1} \ICheekBox cb2 = new JCheckBox"MySQ") ada(cb2);, ‘JOheckBox cb3 = new JCheckBox("Mlicrosomt Access’); ‘adaeb3); + i Languages Component cass LangPanel extends JPanel ine ‘public LangPanol() { ‘Button bl ~ new JButton|'ISP') ‘edd(t}; ‘Button b2 = new JButton("ASP"); ‘ada(h2); ‘Button b3 = new JEutton("PHP"); ‘ada(b3): + + - ‘eannca/ ublatons” An vo mnt knowing Aatoonced ava Programming 2-15 swings output Scroll Pane +The scroll pane is a rectangular areas in which some component can be placed. + The component can be viewed with the help of horizontal and vertical scroll bars. + Using the JScrollPane class the component can be added in the program, + The JScrollPane class extends the JComponent class. + There are three constructors that can be used for this component - “JSerollPane(Compenent component) IBerollPane(int vscrolibar, int hacrollber) \JSerollPane(Gomponent component, int vscrollpar, int hscrollbar) ‘The component represents the reference to the component. The vserollbar and hscrollbar are the integer values for the vertical and horizontal scroll bars. These values can be defined by the constants such as Constant ‘Meaning HORIZONTAL SCROLLBAR ALWAYS __Italways displays the horizontal scroll bar. HORIZONTAL. SCROLLBAR NEEDED _Itelsplays the horizontal scrollbar if required VERTICAL SCROLLBAR ALWAYS Italways displays the vertical scrollbar. VERTICAL, SCROLLBAR NEEDED. Itdisplays the vertical scrollbar if required, + Following isa simple program which illustrates the use of scrollpane, Step 1: Create a label Step 2: Create a panel Step 3: Use an image with the help of label Stop 4: Add the label on the panel ‘Stop 5: Create a content pane. =f. Technisa! Publestons” ~ Anup frat forinaedlge 2 Step 6 : Create a scrollpane component by passing the image (within a panel) as a component toil Step : Add the the scrolipane component to the content pane component. Java Program import java.awt *; import javax.swing *; public class ScroliPaneDemo extends JApplet { ‘public void init { Container contentPane ‘getContentPana(); contentPane.setLayout(new BorderLayout()) ‘Panel mypanel = new JPanel(); JLabel L1 = new JLabel) Imegelcon i ~ new Imagetcon(‘img jpg"); EL.setLecation(20, 100); L1.setSize(120, 120), L1setleon(); ‘mypanelada(tt) {int vgerelibar = SerollPaneConstants VERTICAL SCROLLBAR_AS NEEDED; int hscrolibar = ScrolPaneConstants HORIZONTAL SCROLLBAR AS NEEDED, 1p = new JScrollPane(mypanel, vscrollbar, hecrollbar); contentPane.addijsp, BorderLayout, CENTER); Applet started, Toxtneel Pubiesions” Anup thn! fr inoaldon Adsanced avo Progremining ‘+ Tree is a type of component that gives the hierarchical view of data. User can expand or shrink the nodes of the tree. ‘© In swing the trees are implemented using the JTree class. This class extends the JComponent. ‘+ The most commonly used constructor for this class is - Tlroo(TreeNodo root) The root represents the root node of the tree. «Using the DefaultMutableTreeNode, it creates a tree node with no root node, the child of root node, specified by user object and it allows only children that have to be specified. It lakes boolean types values either ‘true’ or ‘false’, If you will take ‘true’ that means children node are allowed Step 1: Make use of applet for implementation of the tree program Step 2: Create a tree with root, child and grand child nodes. Step 3: Create a content pane object. Step4: Add the JTree component on the content pane. Java Program import javascswing.*y import javavawt.t) import javax.swing.tree.*: TyeeDeme" width=300 height=200> public class TreeDemo extends JApplet 4 public void init() { Containar contentPane=getCententPane\) contentPane.cctLayout(now BordorLayout()) ‘Defaul:Mutable‘reeNode root = new DefaultMutableTreeNode(‘Root’, tue) DefaultMutableTreeNode ct = new DefaultMutableTreeNede( "Child 1 root.ada(ct): DefaultMutableTreeNode root.ada(e2); ovr DefaultMutableTveeNede("Cild 2"); DefaultMutableTroeNode gel ~ now DefaultMutabloTreeNodo("GrandChild 1") Default MutableTreeNode oz = new Default MutableTreeNodet"GrandChild DefaultMutableTreeNode gc = new DefauitMutableTreeNoda("GranéChild ‘Testrical Publeaions” Anup tuto Hnowledoe “Adtsanced Jv Programing 218 Swings e2.add(get): c2.addlge2), c2.ada(aesy: DefaultMutableTreeNode 3 = new DefaultMutableTreeNode('Child 3°} root. ada(c3 }; DefaultMutableTiceNode c4 = new DefaultMutableTreeNode('Child 4°), root. added); Default MutableTieeNode c5 = new DefaultMutableTreeNode('Child 5°), root. ada(e5): “Tree wee = new JTree(root); contentPane.add\tree); } } Follovring commands can be used to execute the above code D\JavePrograms>javac TreeDemo,java, D.\JavePrograms> Apple: Viewer TreeDemo java [Root Denies ¢ Gicnia2 D orandcriia 1 D oranachiia 2 D oranachia 3 Dcnias Donia Doms Applet started. Tables + Table is a component that arranges the data in rows and columns. + The JTable class extends the JComponent class. The constructor used for table component is - STable( objectif] tablevaiues object [I cclumnheader| The tableoulues indicate the data that can be arranged in tabular fashion. The columnhender denotes the header for each column, Following is a simple program that shows the use of JTable component, TectncelPubiesions” Anup rast fr molec

You might also like