You are on page 1of 181
ENGL COMIUTRN ENGINKERING AND IXPORMATION TECHNOLOGY GROUP . ™ ADVANCED JAVA PROGRAMMING ai] f? Dr. MEENAKSHI A. THALOR ‘MAHESH GURUNANI PRASHANT SOMWANSHL RAJESH YEMUL EE A Text Book OF ADVANCED JAVA PROGRAMMING (22517) Semester - V THIRD YEAR DIPLOMA IN COMPUTER ENGINEERING AND INFORMATION TECHNOLOGY GROUP As Per MSBTE's ‘I’ Scheme Syllabus Price € 160.00 NONIRALI PRAKASHAN nasa ia ont en cps snnce ata Nira Prekashon + 119.8idhaw Pet Jegshr Mon ne, re $002 enn Nira Prokashon + 5 hi 22 Dis an Asn Coleg Pe 101 Eat rairambsiomgtenine com > DISTRIBUTION BRANCHES irl Prokeshon + 4 Glare aretha 25, Maha esas 220m Mot 822300 ta: ran git com Nira Prokashon + ev isa fod Ke Paa "Fe Opp. ak ahs 6032 NacPUR e225 128 a-msnagaetprsnin cn Nira Prokashon + 45915 Br Ann i Rod Dany {nal naebioprgmone or BENGALURU aterm ngs S20 Kamas Mob: S34 rane Hydra Chr atta dor aban rar wor onan Hpi nye ah Opler maw a etapa ee, dino esa stp eu oo aoe eco ero enor oe oot ey nye Recah moos wd oe wh Gem arta passt. Preface We take an epportunity te present this book entitled as “Advanced Tava Programming” to the students of Fifth Semester (Third Year Diploma in Computer Engineering and Information Technology Group). The object ofthis book iste present the subject matter in a most concise and simple manner. ‘The book is written strictly according to the Revised Syllabus (T-Scheme) prepared by Maharashtra ‘State Beard of Technical Education (MSBTE), ‘This book contains sx constructive chepters + Fiest chopter gives an introduction to Abstract Windowing Toolkit (AWT), This chapter also includes AWT contrels ond layout managers. + Second chapter focuses on Swing, Swing components and advanced Swing components are described inthis chapter. ‘+ Third chapter cavers event handing + Fourth chapter gives basic concepts networking, detabase in Advanced Java ‘+ Fifth chopter gives an idee of interacting wi + Servetsis covered in Sith chapter A special words of thank to Shri, Dineshbhei Furia, Mr. ignesh Furia for showing ful fith in us ‘0 write this text book We also thank te Mr. Amar Solunkhe and Mr. Akbar Shaikh of Ws Nirali Prakashan for their excellent co-operetion, We alzo thank Ms, Cheitali Tekale, Mr. Ravindra Weladare, Me, Sachin Shinde, Mr, Ashok Badke, Me. Moshin Sayyed ond Mr. Nitin Tharat We welcome constructive suggestions from our colleagues and students Authors. Syllabus 4A. Abstract Windowing Tootkit (WT) ‘Component, Container, Window, Frame, Panel. Coating Windowed Programs ans Applets. AWT Controls and Layout Managers: Use of AWT Contos: Labels, Butlons, Checkbox, Checkbox ‘Group, Scot Bare, Tox Fed Tox Avo Use of Layout Manages: Flowtayout. BoderLayut, GraLayout, CarsLayou, GridBagLayout, Menu Bars, Meus, Dialog Boxes, Fle Dion, 23 2 Inteducton to Swng: Swing Feat, Diferance botwoon AWT and Swing. ‘Sing Components Apple, lons and Labels, Text Feds, Combo Boxes. ‘Bustens: The Buon, Check Boxes, Rado sions ‘Aavaroed Swing Components: Tsebed Panes, Sol Panes, Toes, Tables, Pregressbar,Teains. MVE Arenteture ‘Te Delegation Event Mel: Evant Sources, Evert Listeners. Event Classes: The Acton Event Cass, The lam Evert Class, The Key Event Clas, The Mouse Event Class, The Text Event Clas, The Window Event Cass, Aspen Clases. Inner Classes. Event Listener Intarfacas: Aetonistener interface, itemLieener iterace, KeyLisenar ntrace, MousaLisene nertae, MouseMtion interface, TexListenernerlac, WindoweLstoneInerlace, ‘Sccket veri Cien'Sorver, Reserved Sockets, Provy Servers, Inemet Adsrossing, ava ad ho Not: Tho Notwoking Gassos ae intoraces InetAdares: Factory Methods, Instance Methods. TCPIP Clert Sockets: Whol URL: Formal, The URI Class. LURLConoein: TCPIP Server Sacks Datagram: Datagram Packs, Datagram Sewer and Cont. 32 53 54 nodueten to JOSC, ODBC. DBC Architects: Two Ter and Thre Tier Modes. Types ef DBC Drivers. Driver intraces. and Driver Manager Ciass: Connection Inrlaco Statement Interface, Proparod ‘Statement interface, ResutSetIntace. ‘The Essential JOBC Program Ha 63 68 65 ‘The Lite Cyt ota Sorat. Creaing Simple Servis: The Sarvet AP, Javax seret Package, Servet Inolace, SenfetConig Interface, ServetConiext Intedace, SarvatRaquest Inieface, Serdeesponse Iniaface, GenevesSerlt Cass. ‘The_javaxseriet nip, Package: HtpServelRequest_Intelace, HipServeResponse. nterace, HipsocsnInteriace, "Cooke Class, HipSeret” Cass, HipSessionévent Class, HipSeesion@indingSvert Case Handing HTTP Requosts and Responses, Handing HTTP GET Requests, Handing HTT POST Requests Cooke and Session Tracking Contents ivoducion Component. Container, Window, Frame and Panel 1a Frame Gass 112. Pane Clase Creating Windowed Programs and Apoets AUT Centols ane Layout Managers 131 AWT Contos S314 Labels 2 Buttons 3 ChackBox '¢ CheckBoxGroup (Fado Buton) 5 Ghoes Contos 6 7 8 tise Serol Bars Tox Fis 1319 Test ea Use o Layout Managers 141) Flowtayout 142 Boraertayout 443 Gnotayout S44 Caray 145 Gratageayou 4148 Mana Bare and Menus te Manu Bar 4462 Mon 147 Diag Boxes 4148 Fle Dialog + Practice Questions ReRReReers 20 2a 23 24 ivodvcion Irreducon to Swing Bi Suing Features 212 MC Arentotire 21.3. Diterance batwaen AWT ana Suing 21k Wodking win Sng 2.1.5 Advarlags and Disadvartges of Swing Swing Gompanents, 221" derame 222 Unpret 223 abel 224 loons 225 JToaFel 226 SToswon 227 Combo Bowes Batons 281 Buon 232 IRadoBuon 233 checkbox ‘dvancea Suing Components 2411 Tabbod Panos JTabbosPare) 242 JscoiPane 243 JTree 234 STable 245 JToottip 246 ProgressBar + practes Questene 30 an 32 a 4a 45 46 a inoducton 3 Deegan Event Moe 3 ay events 2 312 Source 3 313 Evont Listener 3 Event Castes 3 521 Aclonéven Claes 3 322 temevent Case 3 323 Koyevent Clase a 324. Nouseévent Class 3 325 Tontevon Case 3 326. Windowevort Class 3 ‘caper Classe 3 Inner Classes 3 vont Lister irteraoes a 551 Aclonustenerietace an 352 emutoneineriscs a 383 Kojictnernerace a 84 MouseistenerIerlace as 385. NouseKotonlisteneriertace aye 356 Toxustonorinaiaco 46 389. Windowtistenor erace a + Praetge Questions 3.25 Tnteducten Sooke! Overview 21.1" Concept of Socket 412 Goanterver Networking 413. Resoned Pons'Sockete 414 Communion Provecols 215 Proxysenvers 18 Inemet Addressing [ava.ana The net (Networking Clasos an Itracos) ‘netadese 451 FacioyMotnods 432 stance Menods Teer Sockets 41" Sorket Gass 442. Serversocket lass 443 whos ore 351 Formato URL. 382 UAL Cis ‘URLconnecton 461 TCPIP Server Sockets Datagram (Datagram Packet, Deagram Sever an Clent) 47.1 DatagramPockots ase 472 DaagamSocket Gass 473. Datagrams Server and Gere + Pracice Questions 50 51 52 iivodueton 51 Inredueton to OBC and ODBC 51 Si bBC 81 Stir voec ap 82 512 O08c 53 5121 oDaC APL 33 5.12. Diference between JDBC and ODBC Sa DBC Architects 84 521 Two Ter Medel 822 Thee Ter ode 8s 53. TYPES OF JDBC Drivers 56 831 Type 1 Diver JOBCIODSC Bridge 58 532 Type2 Driver Natve API Diver 87 533 Type3 Diver: Network Proc, Pue Java Drier 57 534, Typed Drive. Nate Protocal, Pus ava Driver 88 ‘54 Java nteraces and Diver Manager Class 58 5841 Driver nertace 59 542 Drverdanager Cass 59 549 Connoctoninerace sit 844. Statement imerace 512 345 Result nterace 513 54.8 PreparedSiatoment interface 518 55 The Essential JOBC Program S47 + Practiee Questions 524 ‘80. nraaucton et 81 Senet 62 B11 ava Servet Technology 62 612 Senet Vs.Col 83 61.9. Advantages of Sorts 83 6.1.4. Senet Appleston Achitectue ba 815 Typos of Soniote ba E451” Gener Servlets ba 8152 HTTP Sento 8a 62 Lie Cyie ofa Servet 65 163 Creating Simp Soniet be 631 Semel API 610 BT dovaxsorat Package 510 8312 Sot iorace Bi 8.213. SonletCortont tetas 612 831 SenfetContg htrace 513 8315 SonfeRoquost mlrface 614 83.18 SonfetRerponse rtace 515 632 GenoreSenel Gass 616 64 javaxeerdat nip Package 619 Sa Hp Methods 619 642 Tholavarsorothtp Package 619 843. Htpsenot Cass 620 644 HipseratRequeetIverace 621 845 HtpseretRespone Interace 622 848 Cookie Case 623 847. Htpsossion irtaco 624 648 HtpSessioneventCines 625 84.9 HipsossionBindingevent Class 628 85. Handing ip Reaves! and Response 628 651 Handing MipRloquest 628 852 Handing hipResponse 628 883 Handing HTTP GET Request 620 854. Handing HTTP POST Aaquest 629 88 Cookies and Session Tracking est 88:1 Goncoptof Session 631 662 Seren Tracking 632 86.3 Session Management wih HipSession 632 884 Cookies 634 + Practee Questions 838 | Chapter Outcomes... ‘Develop Graphical User Interface (GUD programs using AWT components forte given problem. Create Frame window with the specified AWT components Arrange the GUI components using specified Layout Manager Develop program using Menu and Dialog boxes for the given problem. Learning Objectives... (2 Toundertand Base Concepts of ANT Tolean Component, Container, Window, Frame Fael et. Tostudy ANT conto sch as Lael, Buon, Chaco, Srl Bars, Test ied, Text Ate te Tolesn Concepts ke Mens an Dist Rores EEX mrovucrion ‘+ Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in Java. ‘+ Java AWT components ae platform dependent Le, components are displayed according tothe view of operating system. AWT isheavy weights its components uses the resources of system ‘+ Java graphics APrs (AWD provide a huge set of reusable GUI components, such as button text fel, label, panel and frame for building GUL applications. ‘+ AWT consists of twelve (12) packages but only two packages javaawt and javaawtevent are commonly used 4 Thejava.awt package contains the core AWT graphics classes: © GUIComponent classes such as ,TextFled and Label ‘© GuIContainer classes such as Frame, Panel, Dialog and ScrolPane. (© Layout managers such as FlowLayout, BorderLayout and GridLayout, ‘© Custom graphies clasts such a8 Graphics, Color and Font. 2, ‘TheJava.awt.event package supports event handling. © Event classes such as ActionEvent, MouseE vent, KeyEvent and WindowEvent. (© Event Listener Interfaces such as ActionListener, Mouselistener, Keylistener and ‘Windowdistener. ‘©. Event Listener Adapter classes such as MouseAdapter, KeyAdapter, and WindowAdapter. seen seeee AW classes: ‘+The AWT lasses are contained inthejavaawt package. tis one of Java's largest packages. ‘+ Thecommonly used of ava AWT classes ate given below: 4, | aWtevent ‘Encapsulates AWT events. 2. | Bordertayout “The border layout manager, Border layouts use five components i.e North, South, East, West and Centre. 3 | autton ‘Creates push bution contra. 4. [card.ayout “The card layout manager. Cardlayouts emulate indexcards. Only ‘the oneon top is showing S| cheek Createsa checkbox contr, (| CheckeosGroup | Createsa group of check box controls 7. [choice ‘creates pop-up list. | Container ‘A subclass of Component that can hal other components. 9. |visiog (Creates dialog window. 20. [Event Encapsulates events nL Fitepiay Creates window from whieha file canbe selected, 12 | Flowayout “The flow layout manager. Flow layout positions components left toright, op tobattom. | Frame Creates a standard window that has a tile bar, resize comers, and a menu bar Te [Texthres (Creates a multiline edt contra. 15. Textéield (Createsa single Une edit control 16. | window Creates window with no frame, no menubar. [REM component, CONTAINER, WINDOW, FRAME AND PANEL + The Java AWT contains the fundamental classes. used for oo constructing GUIS. shows Java AWT + Component, Container, Pane, Window, Frame are the fund ‘mental elements in AWT. ‘+ Component is an object having a {graphical representation that can be displayed on the screen and that can interact with the user For examples. buttons, check boxes, ist and scrollbars of 2 graphical user interface + Window is rectangular area wich i displayed on the sereen In. different window we can execute different program and Aisplay different data, A Frame is Disog 8 piel window with 9 ie Tig. Tava wT Rerarchy ‘+ Container is a component that can contain other components. Panel provides space in which an application ean attach any other components, including other panels, 1 The Object class is the top most cass and parent ofall the classes in java by default, Every cass in Java is directly or indirectly derived from the Object class. +The widely used methods of object class are given below. 2 | string tostring() ‘This method return the string representation of | this objec. 2 [void Finalize()thravt Throwable | This method ie invoked by the garbage collector before objet isbeing garbage collected. 2. Component: {At the top of the AWT hierarchy is the Component class. Component is an abstract class that ‘encapsulates all ofthe attributes ofa visual component. ‘+All User interface (Ui) elements that are displayed on the screen and that interac withthe user are subelasses of Component. ‘+ -AComponent object is responsible for remembering the current foreground and background colors and the curently selected text font. ‘+ The widely used methods of Component class are given below: 1_| vols 266(Conponent €) ‘Adda component on another component 2. [ete stszaint wth nt Pgh) Sets sizeof the component. 3. |votd setLayout(Layouttanager n) | Sets thelayout manager forthe component “| void seevisible(boolean b) ‘Sets the visibility of the component. 1 is by default false. [void renave(Conponent_<) ‘Remove component void setdounds(int x, int y, | Used to set the location and size of a single “ne wath, dnt height) | component, and is only useful if ull layout is fused by the container that holds. this ‘component. 3. Container: ‘he Container class is a subclass of Component. It has additional methods that allow other ‘Component objects to be nested within it ‘+ Other Container objects can be stared inside of a Container (since, they are themselves instances of ‘Component. This makes fora multleveledcontainment system. ‘+ -Acontainer is responsible for laying out (pesitioning) any components that it contains. Tt does this ‘through the useof various layout managers ‘+ This class inherits methods from the ava. awt Component and java lang Object. 1__| vols setfone(Font #) ‘Sets the font of this container. 2 [vets setLayout(LayoutRanager nge)_| Sets the layout manager fortis container. 4, Panel ‘The Panel class is a concrete subelass of Container. 1 doesn't add any new methods; it simply {implements Container. A Panel may be thought of a concrete screen component. + Imessence, a Pane is a window that does not contain a title bar, menu bar, or border. This i the reason we don't see a tile bar, menu bat, o border when an applet Is Tun inside a browser. Other components can beadded toa Pane objec by its add) method (inherited from Container), 5. Window: ‘The Window class creates a top-level window. A top-level window isnot contained within any other object: itsits directly on the desktop. +) Generally, we won't create Window objects directly. nstead, we will use a subelass of Window called Frame. 6. Frame ‘+ Frame encapsulates what is commonly thought of as a window: Itisa subclass of Window and hasa title bar, menu bar, borders, and resizing corners. + Thewidely used methods of Frame clas are given below old setritie(string title) Sets the title for this frame to the speciied sting 2.__| wold setbackground(Color bgColor) | Sets the background color ofthis window. FREY Frame class ‘+ We can create stand-alone AWT-based applications. Todo this, simply we need to create an instance ofthe window or windows inside main) For example, the fllowing program creates a simple frame window, ‘+ A-Frame provides the "main window for the GUI application, which has a ttle bar (containing an leon, a tite, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area, ‘+ Frameisa AWT class injava that creates 2 top-level window witha title anda border. + Twoof Frame class's constructors are: 1 Feane(): The first form creates standard window that does not containa tile 2. Frana(Steing title): The second form creates window withthe tite specified by title. ‘+ Thisclase inherit methods from the following classes as per AWT clase hierarchy, (Fg. 1). + java.aut.window + Sava.aut.Contafner + java. aut. conponent + java-tang.obsect “+ Thereare to ways to create Frame through program. They are: 1 By instantlating Frameclass, and 2._By extending Frame lass. Program 1: By instantiating Frame class, Seport Java.oat.*; public class Testavt ‘ restau) ‘ Frame fnenew Frame()s Label 16 = new Label “welcone to Java graphics"); 1. setBounds(10,20,300,50); fn. 204(18); fnssetSize(300, 300); ‘in setvisible(teve); > public static void main(String args(]) ‘ Testowt ta + new Testawt()s =x frecora ina anemes Program 12: By extending Frame dass. Snport java.cut.*; ‘ ‘sinplerane() ‘ setLayout(nuat); setvisible(true)s set5:20(500, 500); setritle("hello"); > public void paint » output eres =a ow ae you? Panel Class ‘+The class Panelis the simplest container class. ‘+ Itprovides space in which an application can attach any other component, including ather panels It uses Flow.ayout as default layout manager ‘Program’.3; Program for pane. Snport java." public class SinplePanel extends Frane ‘ simplerane)() panel setBounds (42,8, 208,200); panet setdackground( color. gray}; .ada(panel) Ff aet5i20(400, 400); .settayout(nult); ‘Fisetvisible (true); > public static vosd main(String args{)) a SinplePanel. penew SinplePanel()s EEA creatine WINDOWED PROGRAMS AND APPLETS: ‘inprevious ection we have seen creation of frame and panel. The frame created by the programmer and displayed on the monitor comes with a ttle bar and three {cons buttons) on the title bar — Minimize, Maximize and Close. The frst two works implicitly and the Clase does not work and requires extra code to close the frame, ‘So to solve this problem one solution i to create a Frame Window within an applet window. To do applet programming we need toextend Applet cass, ‘An applet isnot standalone application. It isa mini program invoked within a larger program, such faz an applet viewer ora Java-enabled World Wide Web (WWW) browser, An applet depends on the ‘Viewer or browser to providea context in which to run. Following are the methods of Applet class: ‘L_ init In tis method, the applet objec is created by the browser. Because this method i called ‘before all the other methods, programmer can utilize this method to instantiate objets initialize variables, setting background and foreground colors in GUI ete 2. start)-To make the applet active, the init) method calls star) method, In star) method, applet ‘becomes active and thereby eligible for processor time, 3. paint: This method takes a java aw Graphics object as parameter. This class incudes many methods of drawing necessary to draw on the applet svindow. This is the place where the programmer ean write his code of what he expects from apple ike animation etc ‘4, stop0: In this method the applet becomes temporarily inactive. An applet can come any number ‘of times into this method in its life cyele and ean go back to the active state (paint) method) ‘whenever would like. Its the best place tohave cleanup code. Its equivalent tothe blocked state ofthe thread 5. destroy(): This method is called just before an applet objet is garbage collected. This isthe end of the Lifecycle of applet It is the best pace to have cleanup cod, Iti equivalent tothe dead state ofthe three. ‘+ Te following program creates two classes named as SampleFrame and AppletFrame, SampleFrame class extends the Frame class and AppletFrame class extends the Applet da + -Awindow of sampletrame Sop() method show and hi Instantlated within the init) method of appletFrame, the stat) and ‘the child window, respectively It also causes the child window to be ‘hoven when the browser returns tothe aplet, ‘Program 1.4: Program for Frame in Applet. Seport jave-opplet Applets Anport Java. out. Frame: {nport Java.out Graphics; public class AppletFrane extends Applet ‘ SonpleFrane f: public vote anit) ¢ = new Samplefrane(“A Frame Window”); FosetSize(25e, 250)3 Fisetvisiole(teue): public void start) ( f.setvisibe(true): > public void stopt) ( fF setvisible false); > public vosd paint Graphics @) { ‘Esdrawstring(°This 15 in applet window", 10, 20); > d Class Sanplefrane extends Frane ( SanpleFrane(string title) { Ssuper(eitle); public vois point Graphics 8) { edrowstring(This 4s Sn Frame window", 18, 48); apn ipa eo FEE awr conrrois anp LayouT MANAGERS f Conolae component ha al sero near wih R/herepleaon in varou ways for Stata eimai aed eons eps tens «Tiger manager mately pertorcoponers wih acontulne Ths hespparice af ‘dows devined by contain ote on that comainond elaget anager aed TCpowton hen + Inediton the contol, rane window an alo Include a tandardstye menu bar Each etry [Ratenabersesncertroy'amen maneol apes fame use can chore men ar Sere entre tae «Into Scion we wll we te sefrund0 meta of component dss pesion he component on habs hre ing at nated atone ageatar ecco FEEL awrcontrois Con are the components hat alow a ue ont wt ja apo n various ways Coma art on concn wep thnt en genesis ee Bop + Sheawrsupperavrou pes commas suc at abe, Pash Bors, eck owes, Coke st, aaa ear oe nee ethane 13.11 Thetis contol sein va abel label pay salle of eon et Abels an object of type Label, and it contains a string, which it displays. «unarePemie crt tht d et upper ony terse he wer Constructors of Label Class: 1, [Laval string strLabel) ‘creates blank/empty label. 2 | Label string strLabel) ‘Creates a Ibel that contains the string specified by st, Thisstring is left justified, 3. | Labe(tringstrisbel, int liginent) | Construct a Label with the given text String of the text alignment. Three alignments are Label. LEFT, [abel RIGHT and Label CENTER. [Label (String stetabed) ‘Construct a label with the given text String in default of let-aligned 5 [user ‘Construct an initially empiy Label Methods of Label Clas: a. | string getText() ‘The getText) method ean be used to read the Labels 2 [void setvext(string striabel) | The setText) method can be used to modify the Labels text 3 [int getAligment() ‘The getalignment) method can be used to retrieve thealignment ofthe txt. [void setAlignnant(nt aligonent) | The setlignment() method can be used to modify the alignment of the tex. Following program creates three labels and adds them to frame window. Program 15; Program todemonstratelabel. Angort.Java.avt.*; class Hyfrane extends Frane ‘ HyFrane(string 5) ‘ super(s): setLayout(nul)s seevistble(true); setsize(509, 300); Later one = new Label(“Label One")5 Later tee = neve Label(“Labet TH0")5 Label three = new Label("Label Three); set the position of controls ‘ne seteunds(50,5, 100,100); ‘wo, setBounds(15@, 56 200,1 ‘three setounds( 250,58 s4a(one); dC 100); 349( three); ) public static voss main(stréne(] ares) ‘ Hyreane = new MyFrane("Denonstrating Frame"); ) ) output: [@ oomeengrome =a PERE] suttons licked or presses. ‘Button class Is used to create a push button contrl, which can generate an ActionEvent when Its ‘+ -Appush button isa component that contains a label and that generates an event then iis pressed, Push buttons are objects of type Button, constructors of Button Class: “L__| Button(String buttontabel) ‘Construct a Button withthe given label 2 [autten() ‘Construct a Button with empty label Methods of Button Clase: | String gettabel ‘Get the label of this Button instance. 2 [wots SetLoben(sering buttonLabel ‘Set the label of this Button instance. 3] void settnebie(boolean enable) Enable or dlsable this Bution. Disabled [hutton cannot be clicked. ‘| void adanctiontistener(aetionListener I) ‘Adds the specified action Istener to receive ‘ction events from this button. [voi FenovetctionListener (ActionListener 1) ‘Removes the specified action listener so that {tno longer recelves action events from this button, ‘6 | Seeing getactionconand( 7. | void setActienConmand(string conmand) Returns the command name of the action event fired by this button, ‘Sets the command name forthe action event fired by this button ‘Program ’.6: Program to demonstrate buttons ‘eport Java. out"; class wyFrane extends Frane ‘ Button ok, canceds yFrane(string 5) ( supen(s)s settayout (mull); setvisible(true); set5ize(50@, 380); fk = new autton( OC") cancel = naw Button("Cancel"); ok. set Bounds (58,50,50,58); cancel. setdounds(128,50,100,50); asd(ot); fsd(eancel); y public statte vosd main(String(] args) ( HyFrane # = new MyFrane("Denonstrating Frans”); y » ‘output [Bdemontatingia. — O xX (oe! [essen] (CheckBox ‘+ -Acheck boxis a control thats used to turn an option on (tru) or off (false) I consists ofa small box that can either contain a check mark or not. ‘+ ‘There is a label associated with each check box that describes what option the box represents. We change the state ofa checkbox by clicking ont. 1+ Check boxes ean be used ind cass ‘constructors of CheckBox Class: ually or as part of a group, Check boxes are objects of the Checkbox 1 | checkbox) ‘Creates a check box with an empty string for ftelabel. 2 | Checkbox(String 12561) ‘creates checkbox with the specified label, 3. | checkbox(string label, boolean state) ‘Creates a check box with the specified label nd sets the specified state “| eheckbox(string Label, boolean state, CheckboxGroup group) 5. | checkbox(string label, CheckboxGroup group, boolean state) ‘Constructs Checkbox with the specified label, set to the specified state, and in the specified checkbox group, ‘Creates a check box withthe specified label, in the specified check box group, and set to the specified state 4. string gettabel( (Gets the label of tie check box. 2 [bootean getseate( Determines whether this check box ie in the ‘onoroff state, 3 | void setLabel(Sering Tabel) Sets this check boxe label to be the string argument. 4 | void setstate(bootean state) Sets the state of this check box to the specified state S| voks adaiten.iatener(Itenistener 1) ‘Adds the specified em Ustener to Feces item events from this checkbox. | void renovertent tener (Itenlistener 1) Removes the specified item listener so that the item listener no longer receives item events from this check box ‘Programa 17: Program to demonstrate checkboxes ‘nport Java.oat.*; public class WyFrave extends Frane ‘ string nsge"*: yFrane() 4 settayout (out) setvisible(trag setsize( 300,380); setTitle("nel10") Lene Checktox(“2ava", False) bt, setBounds(100,100,50,58); ascent): eozanew Checktox( "Cee" False), 2, set8ounds (108,200, 50,51 aedceo2); > public statte vosd main(string argst}) ase ow EERE] checksoxcroup (Radio Button) ‘+ TheCheckBoxGroup clas ured to group thesetof check bx 1+ eis possible tocreate a set of mutually exclusive check boxes in which one and only one checkbox in the group can be checked at any onetime 1+ These checkboxes are often called radio buttons, because they act lke the station selector on a car radio where ony one station can be selected at any onetime. + For erating ast of mutually exclusive checkboxes, we mast fist define the group to which they vwillbelong and then specify that group when we construct the check boxes. comune fect ‘ethods of checkBoxGroup Clas: 1 | Checkbox getselectedcneckbox() ‘Gets the Checkbox component group currently selected. 2 | void setSelectedcheckbox(Ghecibox) | Determines which Checkbox component selected group. ‘Program 8; Program to demonstrate Checkbox group, Seport java.owt.*5 class vyrrane extends Frane { ‘hectbox cba, cbzs heckboxsroup cba Seeing msg = "3 nyrrane(steing £) ( SetLayout (nul: sewvisible(trae) ; Set5ize(369, 300); setTitle(*hello"); tn = new Checkbonsrou() ht = new Checkbon(= ft. setsounds(206, 100, aise, cba) 5. 50)) ("600") false, cbB)s 209, 50, 50); cb2, setsounds (20 scene); > Bublic static void main(String()} ares) { Hyicane # = new Pyrane( PEERY choice controls "The Choice clas is used to create a pop-up list of items from which the user may choose, Thus, a Choice controls a Form of ment. ‘+ When a Chaice component Is inactive, It takes up only enough space to show the currently selected Rem. When the use licks on it, the whol ist of ehoices pops up, and 2 new selection can be made. ‘+ Each item in thelist i a string that appears as a lft justified label in the order itis added to the Choice object. constructors of Choice Control lass: a: TT | Methods of choice Control Class: —— 2 fine counertens() ‘Useful for interrogating the Choice contents '3.__[ string gettten¢int index) | Getan item by index from Oto countitems) “1 4 [int getsetectesingox() ‘Tells which item is selected by number. S| String. getseLecteaiten() | Returns the selected iter’ s text ‘5 [vote Select(int pos) ‘Make a particular cll the default 7 [vote select(string #27) FHghlight the fest cel with text equal = ‘Program 19: Program to demonstrate choice contols. Seport Java. class vyfrane extends Frane ‘ String 95g choice €% yFrane(String 5) 4 settayout (aul) setvisible(true)s sets2e(309, 300); settitle¢"nello"); = new Chotce()s ade "sunday") ada Wonday" ‘aa("Tuesday") ‘0("Wednesday"); Elsetdounds(200, 106, 209, 100); 3éace): > public static void main(string(] args) e 1 iframe f= ee irae > ‘output: EMA ists "The List clas provide a compact, multiple cholee scrolling election list, ‘+ Unlike the choice object, which shows only the single selected item inthe menu, a List object can be constructed to show any numberof choices inthe visible Window. It ean also be created to allow ‘multiple selections. Constructors of Lists Class: a [ust Creates anew sroling ist. 2 [eise(int rons) Creates a new scrolling list initialized with the specified number of visible ines. 3 | List(lnt rows, boolean wultipierde) Creates a new scrolling list initialized to Aisplay the specified numberof rows, Methods of Lists Class: 1 | vold ada(steing Aten) ‘Adds the specified item to the end of scrolling list. 2 [void ada(string Hen, int index) ‘Adds the specified tem tothe serolling lst at the position indicated by the index. 3. | wold addiction ietener(actimttstener 1) ‘Adds the specified action listener to receive action events from this ist. [wold acdttentistener (Ttentistener 1p ‘Adds the specified item listener to receive item events from this lit 5_| intl] getselectedindexes() 6 [dnt getselecteazndex() ‘Gets the selected indexes on thelist. Cts the index of the selected item on the ist 7.__| String getselectedtten) ‘Gets the selected tem on this seroling ist | string{) getselecteertens() ‘Gets the selected items on this eroling list 9. |woid clear() Empty the list rogram 1:20; Program todemonstrate lists class nyfrane extends Frane ( string mse = list 5 tyFrane(string 5) { setLayout (nll); Setvisible(srue); Set5i20(300,. 300); Setritie("helo"); new List(S,. true); 1. aad“sunday"} asa “nonaay") Liasd("Tueséay"); 1asd(-weaneseay"): L.setBounds(108, 160, 100, 100); sac); Public static void maint ykrane f= new MyFranet y sna] ares) ¢ ? PERE] scrott pars ‘+ Scrollbar control represents a scrollbar component in order to enable user to select from range of values. Scrolbars allows users to scroll the components. Scroll bars are used to select continuous values ‘between a specified minimum and maximum, Scroll bars may be orlented horizontally or vertically. ‘+ The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb) forthe scrollbar Constructors of Scroll Bar Class: 4. __|seroiiear() ‘creates new scrollbar. 2 | Serottbar(int style) ‘Creates a sell bar with spedfiedarientatlon, thats, Scrollbar: HORIZONTAL or Serollbat-VERTICAL, ‘3. | Serolibar(int style, Specifies the initial value andthe maximal value Sint snitialvalue, along with the thumb size nt thunbsize,int win, int mx) Methods of Scroll Bar Class: 2.__[ane getnaxinun() (Gets the largest value the scrollbar will report. 2. [ine _getninimun() Gets the smallest value the serolbar will report, '3.__| void setvalue(int value) Set the handle atthe value. “4 | void setvalues(ant value, int | Reset the scrollbar to reflect the bounds passed in. Visible, int mininun, int finie) | int getvalue() Gets the current value of the bar. Program 1:11: Program to demonstrate scrollbar. Anport java.aut.*; class nyFrane extends Frane « Serottbar sb: NyFrane(string 5) setLayout(null); setvisible(true); setsize(309, 360); setritle(*hello"); sb = new Scrollbar(Scrolibar.VERTICAL, 8, 1, 8, 166); sbesetBounds(100, 12, 58, 100); ase); > public static void main(Stringl] ares) ( yFrane f = new MyFrane(""); ? ? (ana = ae BERT] text Field ‘+ The TextField class implements asingle ine text-entry area usually called an edit contr ‘+ Text fields allow the user to enter strings and to eit the text using the arrow keys, cut and paste ‘keys, and mouse selections. ‘+ TextField isa subclass of TextComponent Constructors of TextField Class: 4. |Textrield(string strinitiatText, | Construct @ TextField instance with the given ‘int colunns) | inital text string with thenumber of columns. 2 |Textrield(string strinitiaitext) | Construct @ TextField instance with the given {nial text string 3. | TextField(int columns) ‘Construct a TextField instance withthe number oF ‘columns. Methods of TextField Cas 4. | string getrext() (et the current text on this TextField instance. 2 [void settext(string strrext) Set the display text on this TextField instance. ‘Toke note that getText)/SetText) operstes on string 3. [void seteditanie(boolesn editable) | Set this TextField to editable (read/write) oF non- editable (read-ony). 4. | eddactiontistener “Adds the specified action listener to receive action (ActionListener 1) | events from this text feld 5. | void renoveactiontstener Removes the specified action listener so that it no (aetiontistener 2) | longer receives action events from this textfield Program 1.12: Program todemonstrate textfield eport java. cut; class WyFrane extends Frame { {aber 12,125 yFrane(string 5) ( super(s)3 setLayout(oull); set5ize(500, 506); setvistble(true) ; anes Label “Enter User mane"); i.setsounds(se, 109, 200, 50); ‘= naw Tertfse14(22)5, ‘1. setsounds(150,, 186, 190, 50); seat); mace): 12snes Label “Enter Password"); 2,setsounds(58, 200, 108, 56); 12 = new TextField(8); ‘e2.setdounds(150, 200, 100, 50); sa setfcnacnar(*)5 24a); acd(t2); > public static vosd matn(stréng(]} args) HiyFrane = new MyFrane("Frane"); FEE] rec ares coe ee atin anabcne ert 3, | Textarea) ‘Constructs a new text area with the empty string as text 2 | Textarea( int rons, Constructs anew textarea with the specified number of Sint columns) | rows and columns and the empty string as text. 3. | Tertarea(string text) Constrcts a new text area with the specified text | Tertarea(string text, Constructs 4 new text area with the specified text and nt rows, int’ colunns) | with the specified numberof rows and columns, 5 [Textdrea(String text, int | Construct a new textarea with the specified tex, and rows, int coluens, dat with the rows, columns, and scroll bar visibllity as scrollbars) specified below (@SCROLLBARS BOTH: create and display both vertical and horizontal serollbars, (i) SCROLLBARS HORIZONTAL ONLY: Create and isplay horizontal scrollbar only. (Gi) SCROLLBARS NONE: Do not create or display any sollbars forthe text area, (ie) SCROLLBARS. VERTICAL, ONLY: Create and display vertical serollbar ony. Methods of Textarea Class: 1, | vote setcolums(int columns) | Sets the numberof columns for this textarea, 2 [ine getColums() ‘Returns the number of columns in this textarea. 3. [tne gettows() Returns the number of rows n the text area. 4 | vold insert (string str, Inserts the specified text at the specified postion inthis nt pos) | text area 5._| wold append (String str) “Append the given text tothe text area's current text 6. | void replacetange(String str, | Replaces text between the indicated start and end {int start, intend) | postions withthe specified replacement txt, ‘Program 1.3; Program to demonstrate textarea, Inport java.ant.*; class tycane extends Frane ( iyerane( string 5) ¢ super(s); settayout(null); s0t5i20(500, 500); setvistble(true); 1 = new Texttrea(ne)s ‘ta. setBounds(50, 188, 109, 160); aaa); > public static void main(string{) args) ( HyFrane = new MyErane("Frane”); > output: (ae = ox FEB use oF tavour MANAGERS Layout rans the eragenent of compen Win He conaine The tak of yong the resrae done aunty bye pet hanaper Alo te conponens that we be the SSiashavebonpoutoned yh fei leu ager + Thelnyut manger sty the etayou{} method focal! setlayou() it made, then the Binal gont mabey «Sth cote re (nd or the a ne the tao manager ed pain tbboftnecomponens ni. + Spruetapo( tod ta the lla gene form/eyta vata ton taronerse Instead) tiegeadfoseeenets he detredinjout menaer «fre hel werd preefined njent Manage csr’ eat manager ce re ound nthe Jira jchcpe lent teens coe apna ephacotosents « Sooriyoc angers st hh ae Sorbo er teome we ca aoe the yout macager that etivodrapneten «Theyre pete provi ve aout manager asses as ven below 1 Fowtayeus arangescomponentsn vant eve 2. Burerayot anges components dng tess he containeandin the il Cantayoutmungesonporens n'a ony oor ease atetme 4 Guaneginyou alg conpnets analy on vria compote of eet 5. criiayot Arage components in hedength ows and columns Flowlayout ‘+ FlowLayout is the default layout manager. FlowLayout implements a simple layout style, which is cee ct ree at «Components ae out fromthe upper core fot and tp to bottom, When no mare Se ee ee a en ane serene oe and ion thee aitkara sake conan of wines cles ‘Sr.No. | ‘Constructors ‘Description 1 | Floayeut() ‘Constructs anew FlowLayout with a centered alignment anda defaults-unit horizontal and vertial gap Z| Flosayeut(nt atigny Constructs anew Flowlayout with the specified alignment and a default Sunit herlzontal and vertical fap. We can use one of the followings aligment Flowlayout LEFT (or LEADING), FlowLayout RIGHT (or TRAILING), or FlowLayout CENTER 3 | Flostayeut(int atta, ‘Creates a new flow layout manager with the Indicated nt ngapr int vgap) | alignment and the indicated horizontal and vertical ps 1 [int getaligonene() (Gets the alignment of this layout. 2 [int gegap() (Gets the horiontal spacing. 3. [int getveap() (Gets the vertical spacing “4.___[ dnt setalignnent (ine) Specifies the alignment of his layout [int setigap(ine) Specifies the horizontal pacing. [int setveap(int) Specifies the vertical pacing. ‘Program 1.14 Program for Flowlayout. Anport java.out.*; public class FlowlayoutDeno extends Frome ( private Button bent, ben2, 8tn3, tnt, btns, ben: public FlowayoutDeno () ( setLayout(neu Flowiayout()9s beat = new Button( “Button 2°); aagcoenn); bend = new Button(*Button 2°); aag(ote bas = new Button(“Button 3°); aagcotn3); bend = new Button(“Button 4°); ada(bent); bens = new Button(“Button §°)5 1a(vens); beng = new Button( "sutton 6°); aacbene); retTitle(*Flow avout Deno"); setsize(289, 150); setvistblectrue); y public static void main(Stringt] ares) ‘ ) > output [rintyeadow — OX Sa ome om al ‘aas) sane) new FlowtayoutDeno(): BorderLayout ‘+ The RorderLayout class implements a common layout syle fr top-level windows. ‘+ 1thas four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north (upper region), south lower region) east eft region), and west (ight region). The middle area is called the center (central region), ‘+ Fivezones, one foreach component, as canbe seen in Fig. 12 Fipa2 constructors of BorderLayout Class: 1. | Bordertayout() Creates anew layout manager without spacing between regions. 2 | RordertayoutCine, int) Creates @ new layout manager with the spacing horizontal and vertical specified. By default hgap=0, vgap=0 Methods of BorderLayout Class: 1 int-getigap( Gets the horizontal spacing. 2 [ant-getvgsn (Gets the vertical spacing. 3.__[woid setigap(int) Specifies the horizontal spacing. 4. [oie setvgap(int) Specifies the vertical spacing ‘rogram 1.15; Program to demonstrate BorderLayout Inport java.ant.*; public class Bordertayoutbeno extends Frane { private Button bemorth, binSouth, btncenter, btnkast, btmest; public BorderLayouteno() ‘ setLayout(neu BorderLayout(2, 3)): Demoreh = new Button( ORTH") add(btntorth, BorderLayeut NORTH); bensautn = new Button( SOUTH"); aad(btnsouth, Border. avout SOUTH); bencenter = new Button ( CENTER”); aad(btncenter, BonderLayout CENTER); btngast = new Button(“EAST"); fad(btneast, Border ayout. EAST) 5 beniest = new Button("MEST"): add(btrkest, Border‘ ayout NEST); SetTitle(‘aorgertayout Deno") setsize(280, 150); setvisible(true);, > public static void main(string{) args) new Border ayoutDena( ) > Bel crictayout riayout lap oot components In 8 te: imental ei ‘When we instantiate @ Gridlayout, we define = ‘the number of rows and eolumns as shown in Fig. 13, ‘The Grid layout manager places items in rows (feo right and columns (op to bottom, ‘The number of rows and columns is defined ‘when the Grid layout manager is created Fig 13: Grdtayout ‘constructors of Gridlayout Class 1. | Geidtayout() Creates a Gridlayoutmanager with a defaultrow anda column. 2% | eietayout(int, int) Creates @ Gridlayoutmanager with the number of ows and columns specified. 3% [GeidLayout(int, int, ine, tnt) | Creates a Gridlayout manager with the number of specified rows and columns and alignment. horizontal and vertical spacing data, By default: rows, cos=0 agape0, vgap=0. ‘Methods of GridLayout Class: 4. | ant getcolums() ‘ets the number of colurnnsin the layout. 2. [int getHan() (Gets the horizontal spacing 3. [int gettows() (Gets the number of rows ofthe layout 4. [int gewvgap() ‘ets the vertical spacing 5. [Ane setcolums( Specifies the number of columns in thelayout. [int setngap(int) Specifies the horizontal spacing, 7 [int settows() Specifies the number of rows of the layout 8. [int setvgap(int) Specifies the wertieal spacing. ‘Program 1.16: Program to demonstrate GridLayout, Seport Java.out.*5 public class GridlayoutDeno extends Frame ( private Button bint, ben2, btn3, btnd, bn, btn: public Gridtayoutdero() { ‘setLayout(new GeidLayout(s, 2, 3, 3))5 bent = new Button("Button 3°); aed(oent) benz = new Button("Button 2°); aca(oenz); be aca(oen3); bot asaiotna) bens = new Button("Button §°); aa(btns); btné = new Button("Button 6°); aea(oens) setTitlo("6ridtayout Dano"); setsize(280, 150); setvisible(true); ) few Button¢"Button 3°); We Button¢*Button 4°); public static void main(String] args) ¢ net GridLayautDeno(); Beef ceratayout ‘©The CardLayout manager provides the means to manage multiple components, displaying one at 2 ‘time. Components are displayed in the order in which they are added tothe layout, ‘+ The class CardLayout arranges each component inthe container as a card. Only one card is visible at ‘atime, and the container acts as a stack of cards, constructors of CardLayout Class: 1 | Candlayort() ‘Creates a new layout manager without spacing ‘between regions | Gardtayout Cine, int) ‘Creates @ new layout manager with the spacing ‘horizontal and vertical specified. Methods of Class: 1 | void First Container) Displays the first component added to the layout container specified. 2__[nt gethaapO (Gets the horizontal spacing. 3.__[ int getvgapC Gets the vertical spacing. “4, | void tast (container) Returns the last component added to the layout container specified. 5 [void wext (Container) Returns the next component added to the Tayout ‘container specified. % [void previous (Container) Displays the previous component added to the layout container specified. 7__|void setngapCint) Specifies the horizontal spacing. [ota setvgapcint) Specifies the vertical spacing. Program ’L17. Program for Cardtayout ‘eport java. oat"; class CardLayoutdeno extends Frane ‘ CardLayout card = new CaréLayout(20,20)5 Cardtayoutveno() ‘ setritle(*cardtayout in 2ave Example"): set5ize(220, 158); sowvistblectrue) ; setLayout(card)s Button atnfirst = new Button(“First “); Button etnSecand = naw Button ("Second"); Button atathird = new Button(“Third"}; aaa(tafirst "Cardi"; 244(BtnSecond,"Card2"); 24a(staTaied,*Card3"): ) public static void main(String args{)) ‘ CcrdLayoutOons Frame = ns Carat ayoutomo(); GridBaglayout ‘The GridBagtayout layout manager is the mest Ponerf ad Mele ofall the predefined lay Citmgesbutuerscptioted we + nine crctayeut where he component are arranged inva racangiar gid and each component tn the container forte to be the sane. see, in Gridbaglayot, components are ako arranged in rectangular gi but can have dfferent sie ad can an he cccipy multiple rows or clus, 1.) +The cue codnapuayout arranges component I 8 ‘horizontal and vertical manner. we ig. 14:OridBaglayout + Aorineglayut layout manager reuze ato information know where to pt. cmponent in 2 container helper dau caled raageonsrins provides ol hie norton + specifi contntso owe poston a component howto dite the component and Row reseeand ign hem ‘+ Each component in GridBagLayout has its ov set of constraints, 0 you have to astocinte an object oftype GridnagConstralts with each component before adding component tothe container. +_ instance variables to manipulate the GridBaglayout object Constraints are 1 erie and griy ‘These contain the coordinates ofthe origin of the grid. They allow at specific position of a component positioning, By default, they have GrigagConstraint RELATIVE value which indicates that a component can be stored tothe right of previous, eriawiath, sridhoiehe Define how many cells will occupy component (eight and width). By ‘default i 1 The indication is relative tothe other componente ofthe Line ‘or the column. The GridBagConstraints REMAINDER value specifies that the next component inserted willbe the last ofthe line or the current column. the value GridBagConstraints RELATIVE up the component afterthe last component ofa row or column. ‘Defines how toresize the component whichis smaller than the guid cel GridBagConstraints NONE retain the orginal size i, Default GridagConstraints HORIZONTAL expanded herizontaly GridagConstraints VERTICAL expanded vertically GridBagConstraints BOTH expanded tothe dimensions ofthe cll pate, ipady ‘Used to define the horizontal and vertical expansion of components. not ‘works if expansion is required by fil The default values (00) When a component is smaller than the cel in which itis inserted, can bbe positioned using this variable to define theside from which the control should be aligned within the celLPossble variables NORTH, NORTHWEST, NORTHEAST, SOUTH, SOUTHWEST, SOUTHEAST, WEST and EAST. é weights, weighty Used to define the distribution of space in case of change of dimension ‘Program 1.18: Program for GridBaylayout Inport java.avt.*; class Gridsagtayoutbeno extends Frane ‘ ‘ridbagLayoutdeno() ‘ aber ablNane = new Label ane"); TextField txtnane =new TextField(10); Label 2blcoments = new Label(“coments"); Texthres TAreaConnentsonew TextArea(6,25)3 futon btnsuonit = new Button("Suns setLayout (new Gribaglayout()); Gridbagconstraints ge new GeidtagCanstraints(); ad 1bINane, gC,0,0,1,1,8,0);, aadbethame,26,1,0,13,8, 2) 5 add Ibdcoments, 802,14 140.8); ada(TareaComents 844111, 1,068); add(btrsubatt,gc40,2,2,140,20); void add(Conponent comp, cridBagConstraints gc,int x,int y,int wine hy int wxstat wy) ‘ eseritx = x3 csgrdawtdeh = ws ccerdanesent= hy seweignee = camelgnty = 0 44(con, 86); , ) lass Gridogtayoutdovatxanple ‘ public static void aain(steing args[]) ‘ GrtsBagLayoutdeno frane ~ new GridBaglayoutDeno()s ‘Frone.setTiele("GridBaglayout 9 2a ‘Frome, setSize(300, 280); rane setvisible(erve): example"); FEW Menu Bars and Menus + A toplevel window can have a menu bar Oona sssociated witht. ‘+A menu bar displays a lst of top level menu. choices. Each choice is associated with a drop down menu. ‘+ Fig. 15 shows menu hierarchy. Fig 15:The Mena Component Hierarchy Menu controle are listed in following table ‘Menu Component: [ts the top level cass fr all menu related controls. ‘MenuBar: The MenuBar object i associated with the top-level window. Menultem: The items inthe menu must belong tothe Menuftem or any ofits subdlass. ‘Menu: The Menu object isa pull-down menu component which Is displayed from the menu bar, '5.___ CheckboxMenultem: CheckboxMenultem is subclass of Menulter. ‘6. | PopupMenu: PopupHenu can be dynamically popped up at a specified position within & component. ** Creation of menus invelves many steps tbe Tellowed inan order Following ae the st step: create menubar. Step2 : Add menu bart the frame, step3 + Create menus. Step4 : Add menus tomenu ba. step : Create menu items step6 : Add menu items to menus. step? : Eventhandling, PERE Menu sar ‘+ In general, a menu bar contains one or more Menu objects. Each Menu object contains a list of ‘Menultem objects. Each Menuftem object represents something that canbe selected bythe user. ‘+ Since, Menu is a subclass of Menultem, a hierarchy of nested submenus can be created. Its also possible to include checkable menu items. ‘+ These are menu options of type CheckboxMenultem and will have @ check mark next to them when, they are selected. ‘+ For creating a menu bar, we first ereatean instance of MenuBar. This class only defines the default constructor MenuBar() which Creates 2 new menu bar. Next, create instances of Menu that will define the selections displayed onthe bar. ‘constructors of MenuBar Class and Menu Class: | menutar() ‘create menub 2 [menu ‘To create default menu 3. | nenu(strang nave) To createa menu with name 4 enu(string nane, fo0lean tearof#) | Removableistruemeans menu canbe torn off ‘Program 1.19 Program to demonstrate menu bar nport java. oat." public class MonuBeno extends Frane ‘ public Menueno() ‘ enter Bar = new MenuBar(s setNenuBar(n8ar); // add nenu bar to frane Nenu files = new Menu("eslors")3 Nenu exit = now Henu(*Exit"); ear.ada( tes); 11 368 mons $0 nen bar rar aad(exit); setTitte(Wens Deno"); setsize(469, 406); setvistblectrue) ; ) public static void main(string args{)) ‘ re enudeno(); > ) output: [Mestre ‘The Nenu class represents pull-down menu component which s deployed from a menu bar. ‘+ Each Menu object contains alist of Menultem objects, Each Menultem object represents something that canbe selected by the user. constructors of Menultem Class: | menusten() “Tocreatea default menu iter | monutten aca(menutten ml) 2 [Nenuiten(string Gtennane) | Create Menu item by using name of menu item. 3. [Menutten(String Stennane, | Create Menu item by using name of menu item and Menushortcut shortcut) | shortcut ‘Method of Memultem Class: ‘Adds the specified menu item to this menu. 2. [vote add(string Label) ‘Adds an item withthe specified label to this menu: 3. | vote addseparstor() ‘Adds a separator line, or @ hypen, to the menu at the current postion, 4. [Menutten getiten(int index) — | Gets the item located atthe speified index ofthis menu. 5.__| ant getttencount() ‘Get the number of items in this menu. 6, | void insert (Nenurten Imserts a menu Item into this menu at the specified enusten, int index) | postion 7 [void irsert(String Iabel, Inserts a menu lem with the spediied label Into this int index) | menu atthe specified postion. | void insertSeparator Inserts a separator at the specified position, (ine tngex) 3 | Boolean asTeardif() Indicates whether this menus tear-off menu. 10, [vote revove(ant index) Removes the men item at the specified index from thls void renove (WenuConponent stem) ‘Removes the specified menu item from this menu. is] e void renavealO) ‘Remover lliteme from this mens ‘Yu can create checkable menu item by using class CheckboxMenultem, which isa subclass of ‘menuitem, Ithas the following constructors: © Checkbontenstten() © Checkbowanurten(Steing itennate) 2_ChechbosMensTten(string itennane, 8o0lesn on) Program 1.20: Program for menus Inport javavavt.*; ‘ public Nensoeno() enuBar mbar = naw Menutar(); sevtenusar(ador); 11 968 sen bar to frame ena files = new Henu("calors"); Hens exit ~ new Heru("Ea*"); ‘ar. ade( F805); 11-268 wenus to manu bar ‘or adaexit); enutten mit = new Menurten( RED"); sles. sada); Stes adé(new MenuTten(GREEN")); les. sedseparater(); ‘sles 968 MenuTton("BLUE")); exit. adden Menartem(*Close")); setTitle("Menu Deno"); setSize(400, 400); setuistble(true); ? public static void main(String ares{1) 4 new Meruoeno() ? ? output PEE iatog boxes ‘Adialog boris a GUI object in which you can place messages that you want to display onthe screen. ‘often, we will want to use a dialog box to hald a set of related controls Dialog boxes are primarily ‘used to obtain user input Dialog boxes are similar to frame windows, except that dialog boxes are always child windows of a toprlevel window. Also, dialog boxes don’t have menu bars Dialog boxes may be modal or modeless. 1 When a modal dialog bo is ative, we cannot access other parts of our program until we have closed the dislog box 2. When a modeless dialog box is active, input focus can be directed to another window in our rogram. Thus, ether parts of our program remain active and accesible Constructors ‘ama class: Dialog (Frane parent) ‘This constructor creates an instance of Dialog vith no title and with parent as the Frame owning it. It is not | ‘modal ands intially releable. 2 | bialog(Frane parent, This constructor creates an instance of Dialog with no ‘boolean nodat) | title and with pavent as the Frame owing it IF modal i ‘trie the Dialog grabs ll the wer input of the program ‘until iis closed. If modal is false, there fs no special | behavior assoclated with the Dialog. 3 | bialog(Frane parent, ‘Creates an instance of Dialog with parent asthe Frame ‘String titte) | owning it and a window title of ie It is not modal and is intially resizable. “| ialog(Frane parent, ‘creates an instance of Dialog with parent asthe Frame String title, boolean nodal) | owning itand a window title of ttle If mode is tru, the Dialog grabs all the user input ofthe program unt ii Closed, if modal is flee, thene is no special behavior {ssociated withthe Dialog. Program 1.2: rogram todemonstrate dialog box Anport java.cut. publi class Dialogdono extends Dialog ‘ Dialogoeno(Frane parent, String title) ‘ super(parent, title, false); setLayeut(nen Flowayout() setsize(280, 200); setBackground(Color. yellow); Birtton b= new Button("cancel™”)s aac; ) public static void msin( String ares(1) ‘ Frane £2 = new Frame); Dialogdeno oa = new Dislogoena(1, “hello"); ea. setvssible(erue); ‘Java provides a builtin dialog box that lets the user specify Mle ‘+ Tocreate a file dialog box, instantiate an object of type FleDilog. This causes a file dialog box tbe displayed Usually, this isthe standard file dialog box provided by the operating system, constructors. umn 1. | Filepialog(Frane parent) | Creates file dialog for loading a file 2, | Fitebielog(Frene parent, | Creates Fle Dialog box where parent isthe owner ofthe string boxtlane | dialog box and boxdlame isthe name displayed in the box’ ite ba 3. | FiteDisiog(Frane porent, | Creates File Dialog box where parent isthe owner ofthe {nt how) | dialog box and boxdvame isthe name displayed in the bor’ tile bar If how is FleDialog LOAD, then the box is selectinga fle for reading. I how is FlleDlalog SAVE, the boris selecting a file for writing ‘Program 1.22: Program to demonstrate standard lle dilog box. seport 41 class Sanplefrane extends Fane ‘ SonpleFrane(String ttle) 4 string boxian super(eitle)s > » ‘lass Faleptalogoeno ‘ public static vosd main(String args[]) ‘ rane £ = new Sanlefeane(“File Dialog Oem"); Frsetvisble(true)s Fisetsize(t0e, 260); FleDlalog #4 = new FSleDiaLog, “Fite Balog"); ‘a.setvisble(true)s , ) ouput: = ose 2 Scwmee a sceem = ew Sora a {go x * rl = = GE 1 Whatis aWT? 2. Explain AWT dass hierarchy dlagrammatical. 3. Whatarediferent WT controls? 44 Construct listo display the booklist as shown below: ()Javain2adays (i) co made zasy i) C Programming (i) system Analysis and Design. ‘What i Frame? Explain with example. ‘What i Panel? How to create it? Describe with example. Whats layout? stout diferent layouts and explain any one in detall ‘Explain checkbox contol with suitable programming example. 10. Write a program to design a form using components textbox, text fed, checkbox, buttons, ist and handle various events related to each component. 1, Writea program to design a calculator using Java components and handle various events related toeach component and apply proper layout tot 12 Writea program to demonstrate use of GridLayout. 1. Writea program to demonstrate use of FlowLayout. 14, Writea program to demonstrate use of CardLayout 45. Writea program to demonstrate use of BorderLayout. 16, Writea program to create a menu bar with various men items and sub mens items. Also create aacheckable menu item. On clicking a menu Item display a suitable Dialog box 17, Write a program to increase the font size of a font displayed when the value of thumb in scrollbar increases at the same time it decreases the size of the font sehen the value of font decreases, 18, Whats label? How to create it? Explain with example 19, With the help of diagram explain seroll bar control 20, What is ment and menu item? 21, Whatis dialog box? 22. How tocreate menus in AW” Explain with example. 23, Desribe fle dialog with example Chapter Outcomes. Dirt brween AWT and Swing onthe eien oper 13 Develop Graphical User ttrface (GUD programs using Swing components forthe sven problem. &_Lsethe given pe of buton in av based GUL Develop Gaphial User Interface (GU programs wing advanced Swing components forthe given problem Learning Objectives... TS) To earn Basic Concepts of Swing || To understand Components of Swing Applet, cons, Combo Boxes Button, Check Boxes ste) SH To lear Advanced Components of Swing (Tabved Panes, Scroll Panes, Tees, Tables ete) 8 Tostudy MVC Architecture FBI mrropucrion ‘+ Soring is a GUL widget toolkit for java. Its part of Oracles java Foundation Classes QF) an API for providing a Graphical User Interface (GUI) for Java programs, ‘+ Swing Is the User Interface (Ut toolkit of Java Foundation Classes JF). When Sun developed the fxiginal version of Java, it introduced the abstract Windowing Toolkit (AW, which drew user Interfaces based on an abstract layer that set on top of the native windowing toolkit. This caused many problems, as the abstraction tended to blur when faced with the peculiarities of many windowing platforms. “+ To resolve these isues Swing were introduced ap a more sophisticated toolkit with much better cross platform support swing are based on AWT, othe core AWT itil pat of Java ‘+ swing was developed to provide a more sophisticated set of GUI components than the earlier [Abstract WindowingToolk (AW. ‘+ Swing has more powerful and flexible components than AWT: In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as {abbed panel, serell panes, tees, tables, and soon, ‘+ Swing APis set of extensible GUI components to ease the developer life to create Java based Front End/GUr Applications. ‘+ Itisbuitt ontop of AWT APL and acts a a replacement of AWT APL, since, thas almost every control corresponding to AWT controls. FEB nerropucrion ro swine ‘+ Swing is a Java foundation classes brary and Its an extension to abstract windowing Toolkit (AW, Swing is actualy part ofa Java Foundation classes OFC). “+ Siving is an extension to the AWT components which provides feature of pluggable look and feel for ‘he components it provides classes to design lightweight components en ‘+ Swings set of clases, this provides more powerful and flexible components than are posible with the AWE. In addition to the Tamer components, swing supplies several excing additins, Inching tabbed panes, serol panes, tees, and tables. ‘+ Even familar components such a buttons have more capabilites in Swing. ‘+ Forexample, button may have both an imageanda text string associated with + Unlike AWT components Swing components are. not Implemented. by platform: specific code. Instead, they fhe written entirely in Ja and, therefore, are plat form: Independent. The term lightweight s used to describe seh elements + Fig. 21 shows the class hierarchy of the Swing GUI lasses ‘+ component represents an object with graphical repre fentation. Al Container is 2 Component that can contain Fipzaawrusdswingciinss bother SWING components * : '+ Ajcomponent is a bate clase forall Swing Ut components, in order to use a Swing component that {inherits from JComponent, component must be in a containment hierarchy whose root a top-level Swing container EY swing Features rious features of Swing are lsted below: Light Weight: swing component are independent of native Operating System's APL as Swing APL controls are rendered mosty using pure JAVA code instead of underlying operating system call 2. Rich Controls: Swing provides a rich set of advanced controls Like Tre, TabbedPane, sider, color picker, table controls and so on. 3. Borders: We can draw borders in many different styles around components using the setborder() method, 4. Easy Mouseless Operation Its easy to connect keystrokes to components. 5. Tooltips: We can use the setToolfipText method of JComponent to give components 2 toot, fone of those small windows that appear when the mouse hovers over a component and gives explanatory text 6. Easy Scrolling: We an connect scrolling o various components-something that was impossible inawe. 17. Pluggable Look and Feel: We can set the appearance of applets and applications toone of three standard looks, Le, Windows, Motif (Unix) or Metal (Standard Swing oo) MVC Architecture ‘+ Siting components fellow the Model-View: Controller (MVC) paradigm and thus ean provide a much ‘more exible Ul “+ Siring uses MC architecture asthe fundamental design behind each of its components ‘+ TheMVC architectural pattern is used in software engineering to allow for the separation of three ‘common features of GUL applications: The data access (ypicaly via a database), © The business logic (how the data wil be used), User interaction (how the data and actions ' ects will be visually presented), Fig 22:MVC Arch oa Tinea Biba ‘Tovar hs end ope defines toe components of uch an arcu, the oll ew and Com wh e olonng interactions + Thecomponens ae 1 Nel Ts provdesthemeasby which ata isreieved an manips 2 Mew Ta repens th vial rfc components othe Grp! Ue Interae Topleaon sich mere the se Te meracton of amevent den nture where honarlnlatedviskesteardand mouse 4. Conall Tin the Mott tvteVew ands thehearof econ oglbyatcating tcergmeeed venta tet + Thelmenttons creapondta the ig 225 allows PT noon begin Inthe ew ough even generate by th we, The conta provides Atenas forth eet be conte sa Bune ayo manip te Peo ee odfertsin wry wh sferssroponat tothe rents eeredby ete, 2. Ine commar nee withthe od! y eter reueninginormatien fom th ta uct bused ner greed cyano mang thes bseon he cena 2. The mut provds the popemming intro which te cotrler must use to access he Tratue Le he cer snot hens del wth he aabse. naar te sean of concn never cen nthe corer Fartemore he model se Pos means trode 304 ques ote databace 4. The en Intec wi the mae nly to know abou ype information and ether data Tbsvacon held inthe moll Theseely wel Ink date tet the, ie Mode tmeracon shouldbe ‘minimal bacure te manpalaon of tants be Soe wit heeent andi ofthe conaler bE pitterence vetween AwT and swing ‘There are many differences between Jave AWT ands that are given below: 1 | AWT stands for abstract Windowng Toolkit. | Swing is also called as JF's Gava Foundation clasees) 2 | AWT components requirejavaawi package [Swing components require javaxswing package. 3. | AWTcomponentsare platform-dependent, [Java Swing components are platform Independent. 44. _ | AWwT components are heavyweight. ‘swing components are lightweight. 5. | AWT does not support pluggable look and feet ‘Swing supports pluggable lok and fea. | AWE provides les components than Swing “Swing provides more powerful componente such as tables, lists, scroll panes, color choceer, tabbed pane ets, Comte represen data View 0) resent Penatn nd cone) 2c an Tierr tween model and ee RY woking wit Sing 7. [AWT does not follow MVC (odel View ‘swing follows MVC. Where, Model (H) While designing any GUI, we need to have & main window on which we ean place or postion the Aiferent visual components. ‘+ Inwing the main window, also called atop level containers the root ofa hierarchy whieh contains all the other Swing components that appear inside the window. Al Swing applications have at least ‘one top level container. ‘+ Every top level container has one Intermediate” container called content pane. This content pane Contains all he visible components inthe GUl window. + Thecontent panes the base pane vaio {pon which All oer components cxnganss | of cotaner objects at placed One ‘ception othisrie sf thereiea ‘nba inthe top ee container Tbe placed oui the content rane + Fig. 23 tustrtes the relationship Between the components dacused above Fig.23:3wingAplcaton Window + Al Swing components names str with For instance the Swing btn class named a Baton Commonly se top level containers re + just ke Aer appistion, 2 Swing aplction requires a topevel container. There are thre top Ieveleonaier sing 1 frame: Used forthe applications main endow ith an icon i, minim /maximie/lose ‘uttone, an optional mens ands content pa). 2. Dialog: Used for secondary popup window (ith ati, cosebuton, anda conten pane). 2: faple: sed forthe ppets pay ares content pane) idea browse’ window + Sinai to ANT, theve ae secondary containers sch a JPanel which ean be ed fo gro and lay rlvant components. Panels ar sn example ofintermedatcntanes BEB) Advantages and Disadvantages of Swing havantager "Swing provides past debugging support for when youbal your om component 2. Suing componentsarelghweght an AWE 4. Sning components fallow the Mode iew Contoer (HVC) prsdlgm and ths can provide a suchmoreexble Ut 4, Swing provides both ational components ke JTable ete snd added functionality replacement of AWT components 5. Swing providesbtin double butering Diasdvaninges “hit cam be slower than AWVT (all components are drawn), when you are ot carefl about progammine 2 Swing components might not behave exact lke native components which lok ike native components 3. trequres java 2 ra separate JAR file ‘SWING COMPONENTS Swing components are not implemented by platform specific code, nea hey are writen entirely injava and therefore ae platform independent. All Swing components name start with eter] + Sing component cle ight weigh ar dos not depend on ay non jaa system clases Sing Components have ther own view sported by java’ look and el dss + Sing conponens have puggble ok a fee 0 tat wih single se of components you can Echeve he sameloo ad een any operating sytem platform BEEN irrame + Te frame top lvel container or window, on which othr Sng component ae place {-Avtrame components used to crest windows na Swing progam extends va at Fame dass Every Pre bec has a rot pane. 1 | Frane() “This constructor creates anew frame without ttle 2 | arrane(string title) “his constructor constructs the new frame with ite Methods of JFrame Class: 1_[ Container getContentane() | This method returns, a Content Pane forthe JFrame. 2 | voss setLayout(Layoutdanager) _| This method sets the tayoutManager forthe [Frame 3. [vote setiMenubar(Menudar) | This method sets the Menu Barto the JFrame. 4. [Vota setTcontnage(Inage imge) | Prntsicon image on Frame ‘+ There are wo way to createa Frame Window: 2 -By instantiting JFrame las. 2._By extending JFrame cass ‘rogram 2.3: Creating JFrame window by instantiating JFrame dase fnport javax.swing.*; public class 2Franedena { dFrane 3f; dFraneoeno() { f= ne 2Frane("nywindow"); Sautton ben = new 2Button("Say Hello"); Hfeacd(ben);—_/15F.getContentPane.adé(btn) for pre-JOK 1.5 versions jf settayout(new Flowayout()): }¥ setoeFaulecloseoperation(3Frane,EXIT_OM CLOSE); Hf. setsize(4ee, 480); Hesetvisiblectrue); ) public static void main(steing{) args) { new 3Franeden(); d > |B Mywindow - o x Program 2.2 Creating Frame window by extending Jrame cass Anport javex. swing. Anport Java.cont.*; public class 3Franebeno extends Frame € Frame $f; aFraneneno() { setTitle("yhindow")s 3Label Ib = new 3Labed -welcone"); dca); settayout new Flowtayout()): SetDefoultClosedperation( Frame. €XET_OW CLOSE); setsize(se9, 200); setvisible( true); > Public static void main(String{] args) ( pe tee Frome ) Output: [ mywindow - oOo xX (Note: jFrameadd) and jFramegetContentPane).ada) both do the seme thing ~ jFremeada) 5) joverridden to call yrrame.getContentPane()add0. n pre-JOK 15 versions you always had to specify Frame getContentFane\) add) explicitly and Frameaddthrew a RuntimeException. ‘+ JApplet is a class that represents the Swing applet. It isa subclass of Applet class and must be extended by all the applets that use Swing. It provides all the functionalities of the AWT applet as ‘well ax support for menubare and layering of components ‘+ Whenever we requir to add a component tit, the component is added tothe content pane. JApplet supports various panes such as rest pane glass pane and content pane 41. Root Pane: Frame Content Pane Swing containers lke JApplet, JFrame, conser ane | Mens sar JWindow and Dialog delegate. their duties to the root pane represented by the class RootPane. inate ‘+The root pane is made up of a content pane, layered pane, glass pane and an ‘optional menubar, other GUL components must be added to one of these roots pane members, rather than to Ghss Pane ‘theroot pane itself, ‘ig.24:DiferentPanesinJApplet Content Pane: ‘This panes actualy sts on one ofthe layers ofa specially layered pane. + The layered pane in Fig. 24 contains several layers meant for displaying different swing components, depending on the GUTS requirements, ‘+ Fig. 24 shows the positon of the content pane inthe speclaly layered pane. The menu bar and the content pane siton the Frame Content Layer. Glass Pane: Itis a member of the multi-layered, root pane It is used to draw over an area that already contains some components, ‘+The content pane makes Swing applet lfferent from regular applets in the following ways: © Components are added tothe content pane of Swing applets, not directly tothe applets © The ayout managers se for the content pane ofa Swing Applet, not directly forthe applet. The default layout manager for the content pane ofa Swing based applet Is BorderLayout. This aiffers from the default Layout Manager for Applet whichis Flowayeut. rogram 2.3: Program to demonstrate glass pane Inport Javax.swing.*; Inport Java.avt.*; m ‘applet codes"3tppletbeno" wiéth=250 heights cfapple> ” public class atppletdeno extends Jépplet { public void paint(Graphics g) ( .drowsteinglwelcone” 300,100); ‘+ One ofthe simplest Swing component container + This classe used to create single line readonly text which describes the other component Labels can ‘A Label object is a component for placing text ina display text a5 well a Images. Constructors of Jlabel Class: ak Createa empty label having no text and icon Z| atavel (String st) (Createa label having some text. 3.___| atabel(anagetcon 1) ‘Creates a label having icon image Methods of abel Class 1. | vold_sethordzontalAl ignnent(int a) | This method sets the alignment ofthe txt. 2_[ string getText() This method returns the text associated with the Label 3. [vole set Text (String =) ‘This method is used to set the text tothe Label ‘4. void seteon(icon 3) ‘This method ses the Icon tothe icon, Program 2.4: Program to demonstrate jlabe. Inport Java.avt.DiensSon; inport Java.avt.Rectangle; fnport Javaxcswing.2Frane} inport Javan swing. 2.206) public class 2FraeDeno extends 3Frane ‘ private 2Label jlabelt = new 2tabed(}s private 2Label jlabel2 = new 2tabel(); public 3Frarebeno() ¢ setLayout( nut }5 setSize( new Dinension(490, 260) ); label setText(Usertame") 5uabert.setaounds(new Rectangle(4e, $5, 82, 25)); 5tabel2.settext (Password); 5Suabe12-setBounds(new Rectangle(se, 95, 68, 25)); aadGuaber2, null); addGiabel, nul); ? public static void main(String args]) ‘ dFranedeno Franecnew 3FraneDem0()5 ‘fra. setVisible( true); ‘Many Swing components such a abel, buttons, and tabbed panes, canbe decorated with anfeon -& ‘Bxed-sized picture, ‘+ Aan icon is an object that adheres to the con interface, Swing provides a Imagelcon class which Implement the con interface which paints an icon from a GIF, PEG, or PNG image. ‘constructors of Icon Clase: 1 [Inagetcon(string filerane) | This constructor creates object with Image which Is specified by filename. | insgeteon(Rl vr) This constructor creates objec with image in the resource identified by url, ‘Methods oF ion Class: 4. | ant gettconsotgnt ) Returns the height of the con in pixels. [int gettconasaenc ) Return the width ofthe con in pixels ‘Program 25: Program of demonstrate icons. Snport javax.swing.*: ” “applet cod v public class 3eppletoeno extends ayplet ( )appletoene” wide public void init() { Tnagelcon icon = new "Inagetcon(C:\\users\ Wize \\bocunents\\NetBeansProjects\\Javatpplication2\\s rel\ear Jes"): Dtabel 31 = new Itabel(“Car*, Acon, Label CENTER); sac ) ) on TextField 1+ The TextField component allows s tenter/edit singe line of ex + Following are the important constructors ofthe subclasses of the TextField class, A. rTectFielé():Constructsa new TextField 2 rrextFielsGint columns): Constructs a new empty TextField with the specified number of columns 3. STextFietd(steing text): Constructs anew TextField initialized with the specified text, rogram 2.6; Program te demonstrate TextField Inport Javon.suing.*s public class JFraneDeno extends IFrame { public 3Franedero() { setLayouttnew Flowtayout()): Dlabel 32 = new Itabel(“TextFielé"); sadn); Mextrield 11 = new sText#ield(4@); aadceea)s Setsize(300, 306); setvisible( eve); ? public static void matn(string args(]) ( ‘ew 3Franedeno()5 ) output: FEMA srextarea "The JFextAres is use to accept several Lines of text fom the user and it has capabilities not found in the AWT cass ‘+ Flextarea class itself does not handle srolling but implements the Serollable interface which allows ittobe placed inside a JScrolPane and thus implement scroling, ‘+ -Alfecarea can becreated using one of the following constructors A. sTextarea(): Constructs nev Textarea. 2 rTextarea(int rows, int coluans): Constructs a new empty Textarea with the specified ‘umber of rows and columns, 3. sTextirea(string text)-Constructs anew Textarea with the specified text displayed. 4 rTewtarea(string text, ine cows, snt columns): Constructs a new Textarea with the specified text and number of rows and columns. rogram 2.7; Program to demonstrate Textarea, Ampere java.axt.*; public class 2FraneDeno extends Ifrane ( public 3Franebena() { setLayout(new Flowtayout())s Label j11 = new BLabel ("Textérea*); aaa(j11); MTextarea tal = new MTextArea(10, 20)5 aaa¢eat); set5iz0(609, 508); setuistble(true); ) public static vosd main(String args{]) ew 3Franedeno(); PEE] combo Boxes ‘+ Swing provides a combo box (a combination of a textfield and a dropdown list) through the ‘ComboBox class, which extends Component. A combobox normally displays one entry. ‘+ However, it ean also display a drop-down lis that allows a user to select a different entry. We can also type our selection into the tex fel. ‘+ The}ComboBox component, similar to Choice component in AWT. + JeomboBox's constructors are shown below 4. conbotox() This constructor creates an empty Combotox instance. 2 sconbobox(OBject{} tens): Creates a JComboBox that contains the elements of the specified array ‘Program 2.8: Program o demonstrate JComboBor. ‘eport Javax. suing. public class 3Franeeno extends Frame ‘ public 2Franeoeno() a string countryl] = ("Tndla", "Aus", “U.S.A", “England”, “Mewzeland”); aconboBox cb = new IonboBox (country); cb, setsounds(50, 5@, 98, 2 aco): setLayout(null); setsize(409, 500); setuistble(true); > public static void main(String args(]) ( new IFreneden(); > y 0 ts a =a ‘= inthis section we study butions in Swing ‘This classi wsed to create a push buttons. This lassi subelass of Abstract Button cass. Constructors of Button Class: 2 | sautton() {create empty button having notitle an con, 2__| sourton(string str) ‘Create button having label, '3.__| soutton(zeon 1) ‘creates button having con image 4 | neutton(string str 1con i) | Creates abutton having string and Icon image. ‘Methods of Button Cass: 1 | void sdsactionl istenertctionl istener obj) | This method is used to register the push Dutton to throw an event 2 [String getrext() “This method returns the text associated swith the button, 3. [void setTexe (String #) “This method is used to set new Label af the Dutton ‘contd. “_] wold wetrorizortal ewtPositien(int pos) | Seis the Horizontal ted postion Feaive tothe graphics. | void setvereicaiTextPosition(int pos) | Sets the vertical text position relative to ‘he graphics, [void settcon( Teor “This method sets the con to the bution. 7. |vots setinenonie(char €) Sels the mnemonic character to the Dutton. ‘Program 29; Program of demonstrate JButten. eport javax.seing. public class Jfranebena extends 2Frane ‘ public 2Franeoeno() ‘ settayout (oul) set5ize(200, 500); setvisible(true); patton 38 = new 28utton( “Conc {b.setdounds(50, 50, 98, 26) 4(36); > public static void main(String args(I) ( ‘ew 2Frameno()3 > ) ups ia a (geet) EB) racioputton ‘+ This class is used to create radio button witha text or icon. Radio buttons are supported by the RadioButton class, which isa concrete implementation of AbstractButton, “+ Once, a radio button ie created they must be kept in one group, which is created by using the uttonGroup lass Radio buttons must be configured into a group. “+ InjRadioPutton only one ofthe buttons in that group canbe selected at any time Constructors of jRadioButton: 4 skadiosutton():Createa empty radio button having no ttle and icon. 2. skadiosutton(string 1):Createa radio button having label 3. akadiosutton(icon 1): Creates a radio button having icon image. 4 deadiobutton(String 1, Teon §):Createsa radio button having string label and icon image. 5. akadiosutton(string 1, 1con s,boolean selected): Creates a radio button having string abel and icon image and default selected if trues passed 6. rkadiosutton(string 1, boolean selected): Creates a radio button having string label and ‘option for default selected policy ‘Program 2.10: Program of demonstrate RadioButton. ‘eport Javax. suing. Anport java. owt." public clast JFranedeno extends 3¢rane ¢ public 2Franeoeno() cs setLayout( new Flowayout()): setsize(469, 508); setvistble(trve); 2Radioautton jot = new 2Radionutton( Dave", true); aéd(irt)s Radioautton jr2 = new Radiobutton(“Cee")s aa3r2)5 > publte statte void main(steing args(]) ew 3Framede()5 Pee ichecxsox chocter isu contre hated red er OF by hewn odesteseoe oon coe eee ee eee eee ener eee sti Muhctaosionisauets howe «‘Bltecgcr cuts ened ets Checkborin. Sng Chacko asthe feng consracrs Deventer) rou aalywoaced ce barhunon ws sotat ons coe eee eee ete ee £ Zacatecas sca senate tanobrenearashedor hase and pce Maes ta iy tc Hoes rere tay ucucdehektoceis tt Saar ee ee er aa a apes ene 1. Recent, eo en, testa set) Cre ah bac th and feat octet tarorunt tanya Sap ates aed f public 2Franeoeno() ‘ setLayout( new FlowLayout())5 setsize(400, 500); setvistble(Crve) dcheckton rt = new Iheckton(“Dava" true); saaciea); ‘ienecksox jr2 = naw 2checkBox("C+#") dCir2)5 > public static void main(string args(]) ‘ ew 3FreneDene(); [ERI avvancen swinc components ‘Swing provides several advanced components such as tabbed panes, scroll panes, tres, tables, ress bars and soon, This sections deals with this advanced component in Swing. ‘Tabbed Panes (JTabbedPane) ‘+ tabbed pane is a component that appears as a group of folders ina file cabinet. Each folder has & title. When 2 user selects a folder, its contents become visible. Only one of the folders may be selected at a time. ‘+ Tabbed panes are commonly used for setting configuration options. Tabbed panes are encapsulated by the [TabbedPane class, which extends Component. ‘+ There are three constructors of TabbedPane: 1. dTabvedPane(): Creates an empty. TabbedPane with a default tab placement of JTabbedPane.TOP. 2, sTabvedPane int tabPlacennt): Creates an empty TabbedPane with the specified tab placement ‘of any ofthe following: ‘TabbedPane.B0TTOH 3TabbedPane.LeFT 3. dTabbedPaneCint tabPlacenent, int tabLayoutPoLicy): Creates an empty TabbedPane with ‘thespecified tab placement and tab layout policy. ‘+ Tab placements are listed above, Tab layout policy may be either of the following: “TTabbedPane.MAP_T#B_LAYOUT ‘+ Tabs are add via the following method: void addTab(String str, Conpanent comp) ‘+ Hore, stris the ttle for the tab, and comp isthe component that should be added tothe tab. Typically, JPanel or subclass of tis added. ‘+ The general procedure to usea tabbed pane inan appletis outlined here: Step1 : Create a TabbedPane object. Step2 : CalladdTab()to adda tab tothe pane (The arguments to this method define the tite ofthe taband the component it contains) step3 + Repeat step2 foreach ta. Step4 + Add the tabbed pane toapplet/Frame. ‘+ The following program illustrates how to create tabbed pane. The first tab is titled Languages and Contains four buttons. Ech button displays the name of@ language, The second tab i ied Colors tnd contains three checkboxes. Each check box displays the name of acolo. The third tab is titled Flavors and contains one combo box. This enables the ser to select one of three Navors, ‘Program 2.12: Program to demonstrate JTabbedPane, eport javax. suing. é “applet cod crappie ” public class JTabbedPanedeno extends Applet ‘ public void intt() ‘ TabbedPane jtp = new ITabbedPane(: $Stp.daTabC"Languages", new LangPanel())5 stp. 2darab( "colors", new ColorsPanel() $ep.a8arab("Flavors", new FlavorsPanel()s aso); ) » class LangPanel extends 3ane) ‘ public Langronel() i button bi = new 28utton( Marathi"): eae: Button b2 = new 2Button("Hindt”); aba): Button b3 = new 2Button("Bonga15°)5 aa(03)5 Button bt = now 2Buston("TaRs2"); eae); > > ‘lass Colorsranel extends Panel ‘ public colorsrarel() ‘ achecksox cbt = new 3checktox( “Red saaeo.)s acheckdox cb? = new IcheckBox(“Green"): aa¢e02)5, eheckllon cb = new MCheckBox(“BIue"); aacens); > > Class FlavorsPanel extends 3Panel ‘ public FlaversPanet() £ acambotox Jeb = new ICondobox(95 jebvoddTten( "Vanilla"; eb. sdtten( chocolate"); eb. ddtten(Stranberry"); a4eo); JScroliPa ‘+ Ascroll pane isa component that presenta rectangular area n which a component may be viewed. ‘+ Horizontal and/or vertical scrollbars may be provided if necessary. Scroll panes areimplemented in Swing by the JScroliPane class, Constructors of srollpane class: 1 | SeroiiPane(Conponent conp) | This creates a scroll pane with the component specified with comp 2% | SerollPane(int vsb, int heb) | This erates «scroll panel with the vab and hab are int constants. that define when vertical and horizontal scroll bars fr this scroll panelare shown. | scrotiPane(Conponent comp, int | This constructor scroll panel creates a combination aby int heb of above both constctor. ‘Constants ofSrollPane Class 1L__|NOREZOVTAL SCROLLEAR ALWAYS | Always provide horizontal sroll bar 72. | WOREZONTAL_SCROLLESR_AS NEEDED | Provide horizontal scrollbar, needed 3. VERFICAL_ScROLLEAR ALAS ‘Always provide vertical soll bar. “4. [VERTICAL SCROLLBAR AS_NEEOED | Provide vertical seroll bar, ifneeded. ‘+ Hore,are the steps that you should follow o use a scrollpaneinan applet: Step1 : Create a Component object. Step2 : Create aJScrllPane object, (the arguments to the constructor specify the component and the policies for vertical and horizontal eerollbats) step : Add the ecrll pane tothe applet ‘Program 2.13: Program to demonstrate JSerollane. Anport java. oat"; nport javax.swing.* ” ‘applet codee"3Serol1Panedeno” widthe30@ heights25@> ” public class 2ScroL1Panedeno extends 2applet ‘ public void inte() ‘ setLayout(nen Sordertayout(): Panel. jp = new 2Panel(); Sp-setLayout(new GeidLayout(20, 209); for (int 4 = 05 4 6 185 404) ( for (int 3 = 05 3 < 185 Jee) ( 3p. aed(new Jautton("sutten * + 6))3 95 > ) {nt v ~ SerolIPaneConstants.VERTICAL_SCROLLEAR_AS.NEEDEDS {nt h = SerolPaneConstants HORIZONTAL_SCROLLBAR AS. NEEDED; 2seroliPane jsp = new 2serollPane( 3p, vs hs sadJsp, Border. avout CENTER); FEED iree Las iipy nD OUD EU CUNUnTN ‘seamen tot een coe npr fe Nig leaning ee sesame oo a a We ‘+ This tresike structure will display folders and subfolders like branches ofa tree one below the other. Tig. 25: Teele Structure ‘+ Stmallar, tree-ke structures ean be created in Java using JTree. Trees are implemented in Swing by the Jire clas, which extends Component. onsractrs free Clase S20. ca Deseiplon 1 dTretiasttabe no) To crate a tee with elements of ash ale senodes airee(Ooject obf 1) “To createa ee with objects a5 nodes 3. atre( testo t) Tocrestea tee with ened ar rotate 4 atreeector To eects 2 with elerent of vectors eden, Methods of ree Gass 51.0 Methods Deseipion ‘TreePath getPathFortocation(int, ity) | It Is used to translate a mouse click on a point of tree toa tree path. Where, x and y re coordinates of mouse click, DefaultMutableTreeNode Class ‘+ is used to representa node ina tree. Using DefaultMutablree Node, you can create nodes forthe root and for allof the data you want to represent inthe tree. constructors Defaultttaietreetode Cass: 52.0. constrains Deripon 1 [befaulttabletreetoie() Createsa node wih no associated wer objet 2. pefasimsaetretode( Object ob) | erestesa node fo whihyoa can atch children 2. pefacimaberretae(Qbect ob, To pei tat ld notes cannot be tached By boolean allowschildren) supplying the third argument as false. Methods of DefaultMutableTreeNode Class: 1. [void adaqmutanleTeeenode child) | Itisused to creat tre node hierarchy. ‘Follow the following procedure for creating Tree: Step : Create a JTree objec. Step2 : Create ajscrollPane object Add tree to sero pane. ‘Step : Add scrolpane to Frame. Program 2.14 Program for Tee Import java.axt.*; Inport Javax.swing.*; public class ITeeedene ‘ arama # srreebena() ‘ fone 2Frane()5 f settayout(new Bordertayout()): 11 Greate top node of tre DefaultnutableTreeNede top = new DefaulemstableTreekode( “Options” DeFaulthutabletreevede a = new DefaulthutableTreatiode( "A" top. add(a); DeFaultmutableTreeviode b = new DefaulemutableTreetiode(” top. 264(0)5 11 Create subtree of "8 DefaultnutableTresNode at ~ new DefaultitableTreekode("A1") a.adé(at); DefavlthutableTeeeNiode a2 = new DefaultitableTreekode(“A2") 2.add(a2)s 11 Create subtree of "3° DefaulthutableTresNiode bi = new DefaultMutableTraehade( add} DefaulthutableTreeNode b2 = new DefaultiitableTreeNade( 82"); .aaa(b2)s DeFaulthutableTreeNode b3 = new DefaultiutableTreeNade(83"); b.add(b3) tree = new Mree(top)s 3Scrolivane jsp = new 3Scrol1Pane( tree); f-add(J29, Border ayout.CENTER); #.setsize( 500,500); f-setvisible( true); ? public static void matn(steing args(]) { ITreebeno jtenew 3Tresdene()s Jrable ‘+ Atableis a component that displays rows and columns of data. JTable class use to create tables for a Gutbased application. '+Wecan drag the cursor on column boundaries to resize columns, We can alo drag acolumnto anew postion ‘+ Tablesareimplemented by the Table clas, which extends JComponent. ‘+ MTableclas defines following constructors drable(abject estal ]{ J, Object colMeadst 1) DTable(int unkows, int honcolunns) drable(vector roweta, Vector columeoata) Here, data isa two-dimensional array of the information to be presented and colHeads is a one- dimensional array with the column headings. The ‘niumRows’ and ‘numcolumns’ are values with which the table is tobe crested. The ‘owData’ and colmnData’ are the vector values by which the {ableisconstructed “+ Hare, are the step for using table in an applet Step1 + Createa able cbject Step2: Create a JScroliPane object (The arguments to the constructor specify the table and the policies for vertical and horizontal sroll bars), step: Add the tablet the scroll pane. Step4 : Add the scroll pane tothe container (appet/treme), ‘+The following program illustrateshow to create and use a table. + Aonesdimensional array of strings is created forthe column headings. This table as thre columns. ‘Atwovdimensional array of strings i created forthe table cells. We can see that each element in the array is an array of three strings. These arrays are passed to the JTable constructor. The table is \dded toa scroll pane and then the scroll pane i added tothe container, ‘Program 2.15; Program to demonstrate able Seport Javax.seing.*: public class 3Tabledeno ‘ dirane F Ddrabledeno() « fee 3Feane(); String rows(ICTe€ (102°, "ante*, 670000"), 302", "204", "780000"), (391", "Sachin", 709000") bh String coluens{]=("1D", MANE", °SALARY"}; sTable jtenew 2Table(rous columns); 5. setiounds( 32, 40,200,380); dstrellPane spunew 3SerotIPane( jt); #.add(s9)3 # et8i20(300, 400); Flaetvisibae(teue); > public static void nain(String{] args) ‘ ew 2TableDene(); > » output: @ =o x © Nae [eae for T0000 fc a 0000 for = JToolTip ‘+A tooltip isa textual pop-up that momentarily appears when the mouse cursor rests inside the ‘components painting region, ‘+ We can add tooltip text to almost all the components of Java swing by using the method setroatTipText(Strings). This method ses the tooltip of the component to this specified strings. ‘+ When the cursor enters the boundary ofthat component a popup appears and texts displayed. ‘+ AsTooiip isa small pop-up window designed to contain informative text about a component when, the mouse moves over it ‘+ Inshort, tooltip isa string has short description and they are used to explain the functionality ofthe compont ‘rogram 216: Program for tool. fnport Javax. sing. "3 public class ToolTiptxanple { public static void main(Steingl] ares) { Frame fonew 3Frane( "Password Field Example"); [Great ing PasswordField and Label aPassiordfield value = new 2xeewordt$el6() value. setBounds (109,100, 100,38); value. setToolTipText("Enter your Passiord”): Label LYenew 2Label("Passvord: 2 setgounds(20, 100, 90,30); {1nééing conponents to frane feadd(value); f.add(11); Fy setsi2e( 300,369); fF setLayout(w11); frsetvistble(true); utput: FRED srrosrsstar vc uneeenag sProgressBar ‘The ProgressBar cassis used to display the progress ofthe ask I inherits JComponent class, percentage of completion af specified task ProgressBar visually displays the progress of some specified task. ProgressBar shows the ‘+The progress bar fils up as the task reaches it completion. In addition to show the percentage of completion of task, it can also splay some text. constructors of ProgressBar Class: >Progressbar() Creates @ horizontal progress bar but no string 2 | rogressser(int min, int wax) Creates a horizontal progress bar with the specified minimum and maximum value. 3. | 3progresstar(int orient) Creates a progress bar with the specified ‘orientation, it can be either Vertical or Horizontal Dy using StwingConstants VERTICAL and SwingConstants HORIZONTAL constants, 4 | porogresstar(int orient, int min, int max) ‘creates a progress bar with the specified ‘orientation, minimum and maximum value ‘Methods of ProgressBar Class: void setstringPainted(toolean t) void Setstring(steing 5) tis used to set value tothe progres Is used to determine whether string should be splayed. ‘ola setortentation(ane orientation) It is used to set the orientation, it may be ether vertical ot horizontal by using SwingConstants, VERTICAL and _ SwingConstants HORIZONTAL constants “| void setwalue(int value) eis used to set the current value on the progress bar, ‘Program 2.47 Program for progressbarin Swing fnport javax.swing.* public class Progresstarexanple extends 3Frane( deroaress8er 3s nt £-0, nun PrograssBarexanple(){ Shanon 2Progress#ar(0,2000)5 5b. Set sounds (40,40, 260,30); Sb.setvatue(6); sp. setsteingpainted(true)s 38430); setsize(250,150);, setLayout(mutl); > public void sterate()( whide(22660)( sh. setvatue(s); sesv20s ‘try Thread. steep( ase) ;}eaten(Exception @){) ? > public static void main(string(] ares) ( ProgressBartxanple nenew Progresszarexanple) esetuisible(teue)s se tterateQs ‘2. What Swing? 2. Enlist various features of Swing? ‘3. With the help of diagram describe following Swing components: (i) scombosox (i) schecnBox (ii) ProcessBar. With the lp of diagram describe MVC architecture ‘what is meant by MVC? Explain the text area Swing components with example. Differentiate between Swing and AWT, 8. Which advanced controls used by Swing? Explain one ofthe min detail, 9. With thehelp of example describe the term combobox. 120. What i check box? How to reateit? Explain with example, 1, Describe JApplet with example 12, What radio button? How tocreate it? Explain with example 1, Explain MVC architecture diagrammatically 18, Deseribe the following terms (@)Serottpanes (i) Tooltip. (i) Tree, Event Handling Chapter Outcomes... 1 Use delegation event model to develop event driven program forthe given problem 1) Unerelevant AWT/swing components to handle the given event. ©) Use Adapter classes in ava progeam to solve the given problem 5 Useinner asses in java program to solve the given problem. Learning Objectives... T= To understand Concept of Event and Delegau 2) Toleaen Event Handling in Java ) Tostudy Adapter Classes and Inner Classes in Java 1) Toleaen various Event Listener Interfaces inv EX wrropucrion Seats Ea = ddeseribes the change in Ea Wiracnevaal _ Racmaedaentonmnmetact’ vent Model Event Handling: “Event Handling is the mechanism that controls the event and decides what should happen if an “+ This mechanism have the code which is known a5 event handler that is executed when an event occurs. Events are generated as result of user interaction with the graphical user interface components en 3. For example, clicking on a button, moving the mouse, entering a character through Keyboard selecting an tem from lst, scrolling the page ae the activites that causes an event to happen. ‘Theevents can be broadly classified into two categories: Foreground Events: Those events which require the direct interaction of user. © They are generated as consequences of a person interacting with the graphical components in (Graphical User Interface (UD, © For example, clicking on a button, moving the mouse, entering a character through Keyboard, selecting an item from lst, erolling the page ete 9. Background Events: © Those events that require the interaction of end user are known as background events © Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events. Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events DELEGATION EVENT MODEL. "There are several types of events. The most commonly handled events are those generated by the mouse, the keyboard, and various controls, such asa push button. Events are supported by the java awt event package. 1m Java both AWT and Swing components use Event Delegation Model (See Fig 2.2), 1n this model, processing of an event is delegated toa particular object (handlers) {nthe program. Event model is quite simple, 2 source {generates an event and sends it to one oF more listeners In this scheme, the listener simply waits until it receives an event ‘Once received, the listener processes the event and then returns, ‘A.ser interface eloment is abe to “delegate” the processing of an event toa separate piece of code. tn the delegation event mode, listeners must register with a source In order to receive an event notification. Event delegation model consists of three parts namely, Event, Source and Listener, Fig. 22: Delegation Tvent Model Events Inthe delegation model, an event is an objet that describesastate change ina source. Itcan be generated asa consequence ofa person interacting with the elements in a graphical user Interface Forex pressing a button, entering a character via the keyboard, selecting an item in is, and licking the mouse souree ‘A source is an object that generates an event (Example, Button). Event sources are components, subclasses of ava art Component, capable to generate events. ‘A source must register listeners in order for the Listeners to recelve notifications about a specifi typeof event ‘Notifications are sent only to lsteners tht register to receive them Each type of event has its own registration method, The general form/syntax of such a method is: public void aderypeLstener(Typelistener el) Here, ype ie the name of an event and lis reference tothe event listeners For eg. the method that registers a moaze motion is called addMouseMtionListener) ‘When an event occurs all registered listeners are notificated and receive a copy of event object and ‘this called ‘multicasting’ the event ‘+ Some sources may allow only one listener to register It icalled“wniasting'the event. Syntax: public void adctypelistener(Typettstener el) throws ova. util TootanyListenersexception 1+ -Asource ls allows listener to unregister an interest ina specific type of event. Syntax: public void renovetypelistener(TypeListenes el) + Following is ist of some ofthe user interface components that can generate the events. tn addition to these graphical user interface elements, other components, such as an apple, can generate events 1+ For example, we receive key and mouse events from an applet, (we may also build our own, components that generate evens) Description of Event Sources: 1. Button: Generates action events when the button is presse. 2. Checkbox: Generates item events when the check boxis selected or deselected 3. Choice: Generates item events when the choice ischanged. 4. List: Generates action events when an item is daublecicked; generates item events when an itemisselacted or deselected. 5, Menu Item: Generates action events when a mens item is selected; generates item events when @ ccheckable men item i selected or deselected Scrollbar: Generates adjustment events when the scrollbar is manipulated. ‘est: Generates text events when the wer enters character, 8. Window: Generates window events when a window is activated, closed, deactivated, dleonifed, ‘confled, opened or quit. EEE] Event Listener ‘= The events generated by the GUI components are handled by a special group of interfaces known as “stenere ‘+ Alistener isan object thats notified when an event occurs. ‘has following two major requirements: 4 It must have been registered with one or more sources to receive notifications about specific typesot events. 2, Itmmast implement methods to receive and process these notifications ‘+ The methods! that recelve and process events are defined in a set of Interfaces found in Javaawtevent + re comme, Noman a} (9-3) Interface defines to methods to. receive notifications when the mouse is dragged oF ‘moved. Any object may receive and process one for both of these events if it provides an Implementation ofthis interface. anor) 4+ Fig.3:3shows Event tisteners. ig. 3.3: Event istenees bd evenrciasses Event class provide a consistent, easy-to-use means of encapeuating evens ‘Almost every event source generates an event and is named by some Java clas, For example, the event generated by button is known as ActionEvent and that of Checkbox is known as ItemEvent. ‘+ Theclass AWT Event, defined within the java awt package, isa subclass of EventObjec. Its the super class, (either directly or indirectly) ofall AWT-based events used bythe delegation event model. + The package javaawtevent defines several types of events that are generated by various user Interface elements ‘+ Bvent class description in Fig 3.4 ar listed below 1. ActionEvent: Generated when a button is pressed, alist item is double clicked, ora menu item fsselecte. seeaee ee wo. -AdjustmentEvent: Generated when scroll bare manipulated. ‘ComponentEvent: Generated when a component ishidden, moved, resized, or becomes visible. ‘ContainerEvent: Generated when a component is added to or removed froma container. FocusEvent: Generated when a component gains or losses keyboard focus, ‘mputzvent: Abstract super clas forall component input event classes Itemevent enerated when a check box or list item is clicked: also occurs when a choice selection is made or a checkable men item i elected or deselected, ‘KeyEvent: Generated when input is received from the keyboard MouseEvent: Generated when the mouse is ‘ragged, moved, clicked, pressed, or released also enerated when the ‘component. Mousewheeltvent: Generated when the ‘mouse wheelis moved. TTextEvent: Generated ‘when the value of a text fea. or text field is ‘changed. WindowEvent: Generated when a window is active: ted, closed, deactivated, elconified, eonified, ‘opened ar qu. BEEY Actionzvent class ‘+The ActionE vent cassis defined in java aw event package. ‘+ An Actiontventis generated when a bution is pressed, alist item is doube-clicked or a menu item is selected. ‘+The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an ation event ALT_MASK, CTRL_MASK, META.MASK, ond SHIFT MASK. “+ tmadaltion, there san integer constant, ACTION. PERFORMED, which can be used to identify action events, ‘constructors of Actiontvent class: Fig 3.4cEvent Castes Hierarchy ‘nt modifiers) 1 [Actiongvent(java.lang.Ooject source, | Constructs an ActionEvent object. ‘int id, javaclang.string command) 2 [Actionevent (java.lang.Object source, | Constructs an A@tonivent object with modifier eys. We can obtain the command name for the invoking ActionEvent object by using the sgetActionCommand() method Syntax: tring getActionconmand( ) For example, when a button i pressed, an action event is generated that has a command name equ tothe abel on that button. FEE] temevent ciass ‘+ AnttemEventis generated when a check box or Ist item Is dlcked 1+ There ae two types of item events, which are identified by the following integer constants: 4. DESELECTED: The user deselected an tem. 2, SELECTED: The wer selected an item, ‘+ IMaddition,ItemEvent defines one integer constant, TEM_STATE_CHANGED, that sgnifiesa change ofstate, ‘+The getitem() method can be used to obtain a reference to the item that generated an event. ts symtaxis shown below: Object getTten( ) ‘+The getitemSelectable() method can be used to obtain a reference tothe ItemSelectable object that ‘generated an event. ts general form/syntax is shown below Ttenselectable getTtenselectabie( ) ‘+ Lists and choices afe examples of user interface element that implement the itemSelectable Interface + The getStatechange{ ) method returns the state change (Le, SELECTED of DESELECTED) for the event It is shown Below ‘ne getstatecnange( ) KeyEvent Class + Onentering the character the Key event is generated ‘+ -AMeyBvent is generated when keyboard input occurs, There are three types of key events, wich are lemtifeaby these integer constants: KEY_PRESSED, KEY_RELEASED and KEV_TYPED, +The frst two events are generated when any Key ls pressed or released. The last event occurs only when a character ie generated, Remember, nat al Key presses result in characters. For example Dressing the SHIPT ey does nt generate a characte. ‘+ There are many other integer constants that are defined by KeyEvent Forexampl, ‘VK_0 through VK_9 and VI A through VK_Z define the ASCII equivalents ofthe numbers and eters. Here, are some others: + me wiconants secre Key cote 1 Eejtenrhave fling enstrators Lfeyeen (Conant rar nt pe, long en, int waiters, Ant cde) 2. keyevenonponent Src, int pe, lant when, Ine esiflrs-int coer chr ch «fie tena ference othe component that aneated te event The peat te event specified byeype: The pom tine at wr hehe nas pases possed in wher The modifiers argument Iuaites whlch mir were pesed when they event ocated Ez] ousctvent class ris event inlestera mouse action occured ina component 1 herearecipt types cmeue events The Mouser das defines the flowing integer constants Thatean be ted ene Foust ctcwen: Te wer ccked the mouse. Z Moust-pnaoorbr Teeter aeggedbe mse 3. must ENTEMED, Te mouseetered component 4 MOUSE-ERTED:The owe ated fom =componest $ Rovst-poved:Themewe moved & must patsstD the mouse spose § Moverstareaseorthemovte we lsd 2 Novst_wiett he mouse wheel wes moved ‘+The most commonly used methods inthis class are getX{) and get). These returns the X and Y coordinate ofthe mouse when the event occurred ‘+ Their form/syntax are shown below: int gate() Ant getv) ‘+ Alternatively, we can use the getPoint) method tocbtain the coordinates of the mouse, It is shown, below Point getPosnt() return «Point object that contains theX, ¥ coordinates ints integer members xand y FER] Textevent class ‘+ Instances of this lass describe text event. These are generated by text fields and text areas when, characters are entered by ausero program. ‘+ Textevent defines the integer constant, TEXT_VALUE_CHANGED. ‘+ Theone constructor for this clases shown below: TextEvent(Object sre, int type) Here, sre is a reference tothe object that generated this event, The type of the event is specified by pe ‘+The Textevent object does not include the characters current in the text component that generated the event, Instead. your program must use other methods associated withthe text component t0 retrieve that information, FEW windowtvent class Pete cbjc of hiss representsthe change in state of window This uwievel cret ls gecrted by swindon abject when is opened, coe, sctated Seat oifeordceoifes or when fos tensered into cut te Winiow + Tre areten ype of window even Te WindonEvet cs deine inet constants hat can be tele dent) tem, Teconsans andthe meanings areshown tere 1 "vaNDOW ACTIVATED Te window was cate. 2. winpoW.cu0stD: The window hasbeen cae Wsbow eLsine: te ue request the window dose Seiwa. panctIvstaiy ue wind wer ected Dow: DEICOMTED: The window wa econ, sDov eatweD rOCUS.Thewindow fined input ous WiNDovtIcOMIFED; he window weenie UNDO Lost FOCUS. Te window ot input oc. Wivbow. OPENED Thewindow wes opened. {WIN NTA Gunman Then ctemoeor tance + Winter’ ists of Cmponensren Tne ot common sed method in this eas i fetingow(} rune the Window Ses tat generate te ere. general ony i Sow bel inane ethno) [EM aparren cases Java provides a special feature, called an adapter class that can simplify the creation of event handler in certain situations, ‘+ An adapter class provides an empty implementation of all methods in an event lstener interface, Adapter classes are useful when we want to receive and process only some ofthe events that are handled by a particular event listener Interface. ‘+ We can define a new class to act as an event listener by extending one of the adapter classes and Implementing only those events in which we are interested. For example, the MouseMotlonadapter lass has two methods, mouseDragged()and mauseMoved). vesewey ‘+The signatures ofthese empty methods are exactly as defined inthe MouseMotionlistener interface. If you. were Interested in only mouse drag events, then you could simply ‘extend MouseMotlonadapter and Implement mouseDragged{ The empty implementation of ‘mouseMoved() would handle the mouse motion events for you. ‘+ Ust below shows the commonly used adapter classes in javaawt.event and the interface that each class implements. Keyacapter KeyListener ousesaapter rousetistener Mausenotionsdapter Rousetotiontistener indowsdater window istener ‘+ the following program demonstrates an adapier. It displays a message in the statusbar ofan applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored +The program has following three classes: 41 AdapterDemo extends Applet. fs init) method creates an instance of MyMouseAdapter and registers that object to receive notifications of mouse events. It also creates an instance of ‘MyMouseMotionAdapter and registers that object to receive notifications of mouse motion ‘events. Both af the constructor take a reference to the applet as an argument. 2, MyMoureAdapter clare implements the mouseCicked{ } method, The other mouse events are eat oe a ied ee dem ments the mouseDragged{ ) method. The other mouse y coe inherited from the MouseMotion Adapter cls. ‘rogram 3.1: Program to demonstrate adapter clases, Anport Java.applet."; 7 cappiet Cover"AdapterDeno” wiethe300 helent-169> */ public class AdapterDeno extends Applet ( ‘public void init) { ‘addouseLstener (new Mylousetdapter (this); ‘ehousenot ont istener(new Hyouseviotionadapter(this))5 ) } ‘lass myousetdapter extends Mouseadapter { ‘AapterDeno adapterdeno; ‘public MlouseAdapter(Adapterdemo adaptervema) { ‘is adapterDeno = agapterdeno; 1) Wandle mouse elickes public void nousecLicked(MouseEvent me) { dapterDeno.showstatus(Mouse clicked"); ? d lass Mytousehotiontdapter extends Mousetotionaéapter ( ‘Adapterbeno adapterdeno;, public Mywousehotiontdapter (AdapterOeno adapterDeto) { ‘his.adapterDena = a¢apterdeno; ) 1) Randle mouse 43 public void nouseDragged(Mousetvent me) { ‘adapterDeno.showstatus( Meuse dragged"); , output: ae a ‘Tas we can see by looking atthe program, not having to implement all ofthe methods defined by the MouseMotionListener and Mouselistener interfaces which saves our considerable amount of effort and prevents our code fom becoming cluttered with empty methods. (EEM ner cuasses ‘+ Inner lasses ae clas within clas. ‘+ inner class Instance has speclal relationship with Outer clas. This special relationship glves Inner class acoess to member of outer class.as if they are the part of outer cass. “There are four types of inner classes ie. member, static member, local and anonymous. 4L. Member Inner Class: ‘Armember clas is defined atthe top level of the class. 1 may have the same access modifies as ‘variables (publi, protected, package, state inal), and is accessed in much the same way as varables ofthat class ‘Program 3.2: Program to demonstrate member inner clas. public class Outerclass { ‘nt outervartable = 180; class Menborclaes ( Ant getSun(int paraneter) ( return innervariable + autenvariable + paraneters > > public static void main(string(] ares) ( ‘outerclass outer = new OuterClass()5 enberclass inner = outer.nex Menberclass(); Syton-out.printlnianer.getSu8(3))3 outer. cunt); > votd runt) Menberclass localzoner = new Menberclass( systen.out.printin(local nner .getsun(5))5, ‘output:

You might also like