You are on page 1of 15

In this section you will learn about the different components available in the Java AWT package for

developing user interface for your program. Following some components of Java AWT are explained !. Labels : This is the simplest component of Java Abstract Window Toolkit. This component is generally used to show the text or string in your application and label never perform any type of action. "yntax for defining the label only and with #ustification Label label$name % new Label &'This is the label text.'() Above code simply represents the text for the label. Label label$name % new Label &'This is the label text.'* Label.CENTER() Justification of label can be left* right or centered. Above declaration used the center #ustification of the label using the +abel.,-.T-/. 0. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger actions and other events re1uired for your application. The syntax of defining the button is as follows Button button$name % new Button &'This is the label of the button.'() 2ou can change the 3utton4s label or get the label4s text by using the Button.set+abel&"tring( and Button.get+abel&( method. 3uttons are added to the it4s container using the add &button$name( method. 5. Check Boxes : This component of Java AWT allows you to create check boxes in your applications. The syntax of the definition of ,heckbox is as follows CheckBox checkbox$name % new Checkbox &'6ptional check box !'* false() Above code constructs the unchecked ,heckbox by passing the boolean valued argument false with the ,heckbox label through the ,heckbox&( constructor. 7efined ,heckbox is added to it4s container using add &checkbox$name( method. 2ou can change and get the checkbox4s label using the set+abel &"tring( and get+abel&( method. 2ou can also set and get the state of the checkbox using the set"tate&boolean( and get"tate&( method provided by the Checkbox class. 8. Radio Button : This is the special case of the ,heckbox component of Java AWT package. This is used as a group of checkboxes which group name is same. 6nly one ,heckbox from a ,heckbox 9roup can be selected at a time. "yntax for creating radio buttons is as follows CheckboxGroup chkgp % new CheckboxGroup&() add &new Checkbox &'6ne'* chkgp* false() add &new Checkbox &'Two'* chkgp* false() add &new Checkbox &'Three'*chkgp* false() In the above code we are making three check boxes with the label '6ne'* 'Two' and 'Three'. If you mention more than one true valued for checkboxes then your

program takes the last true and show the last check box as checked. :. Text Area: This is the text container component of Java AWT package. The Text Area contains plain text. TextArea can be declared as follows TextArea txtArea$name % new TextArea&() 2ou can make the Text Area editable or not using the set-ditable &boolean( method. If you pass the boolean valued argument false then the text area will be non;editable otherwise it will be editable. The text area is by default in editable mode. Text are set in the text area using the setText&string( method of the TextArea class. <. Text Field: This is also the text container component of Java AWT package. This component contains single line and limited text information. This is declared as follows TextField txtfield % new TextField&0=() 2ou can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 0=. The class component is extended by all the A T components. >ore of the codes can be put to this class to design lot of A T components. >ost of the A T components shown below directly extend ,omponent like Button! Can"as! Label etc. Buttons As shown in the example below* a button is represented by a sin#le label. That is the label shown in the example can be pushed with a click of a mouse.

import java.awt.*; import java.applet.Applet; public class MyButton extends Applet { public void init() { Button button = new Button("SUBMIT"); add(button);

$ere is the $T%L code: ?@T>+A ?@-A7A ?B@-A7A ?3672A

?ACC+-T A+I9.%',-.T-/' ,67-%'>y3utton' WI7T@%'8==' @-I9@T%'0=='A?BACC+-TA ?B3672A ?B@T>+A $ere is the &utput: C:'ne(pr#rm)*a"ac %+Button.*a"a C:'ne(pr#rm)applet"ie(er %+Button.html C:'ne(pr#rm)

As the name indicates a Can"as is a region where you can draw things such as circles* triangles* ovals or any other shape. 3asically it is a graphical component that represents a region. It has got a default method which is paint,- method. ,anvas class can be sub classed to override this default method to define your own components as shown below in the example. ??????? canvas."html

%%%%%%% AAAAAAA !.0


import java.awt.*; import java.applet.*; public class My!anva" extends Applet { public My!anva"() { "etSi#e($%& '%);

public void paint(()ap*i+" ,) { ,.d)aw-e+t(%& %& .%& /%); ,.d)awSt)in,("A !anva""& 0/&0/);

$ere is the &utput: C:'ne(pr#rm)*a"ac %+Can"as.*a"a C:'ne(pr#rm)applet"ie(er %+Can"as.html

A checkbox is again a label which is displayed as a pushbutton as shown in the example below. This pushbutton can either be checked or unchecked. Therefore* the state of the checkbox is either true or .alse. @owever* the initial state is false which is the default one. The example below shows the checkbox whose state gets toggled ??????? checkbox.shtml on clicking.

%%%%%%% on clicking. AAAAAAA !.0


import java.awt.*; import java.applet.Applet; public class My!*e+1bo2 extends Applet { public void init() { !*e+1bo2 + = new !*e+1bo2("!*oo"e t*i" option"); add(+);

$ere is the &utput:

C:'ne(pr#rm)*a"ac %+Checkbox.*a"a C:'ne(pr#rm)applet"ie(er %+Checkbox.html

A displayed label ob#ect is known as the Label. >ost of the times label is used to demonstrate the significance of the other parts of the 9DI. It helps to display the functioning of the next text field. A label is also restricted to a single line of text as a button. The example below shows the significance of +abel. In this example* we have added two labels in the applet as shown.

import java .awt.*; import java.applet.Applet; public class My3abel extends Applet { public void init() { add(new 3abel("label one")); add(new 3abel("label two"& 3abel.-I(4T));

$ere is the output: C:'ne(pr#rm)*a"ac %+Label.*a"a C:'ne(pr#rm)applet"ie(er %+Label.html

A scrollbar is represented by a /slider/ widget. The characteristics of it are specified by integer values which are being set at the time of scrollbar construction. 3oth the types of "liders are available i.e. hori0ontal and "ertical. The example below shows the code for the scrollbar construction. The subtraction of scrollbar width from the maximum setting gives the maximum value of the "crollbar. In the program code* 4=4 is the ??????? scrollbar.shtml initial value of the scrollbar* 4E4 is the width of the scrollbar.

%%%%%%% initial value of the scrollbar* 4E4 is the width of the scrollbar. AAAAAAA !.0
import java.awt.*; import java.applet.Applet; public class S+)ollba)5e6o extends Applet { public void init() { S+)ollba) "b = new S+)ollba) (S+)ollba).78-TI!A3& %& $& 90%%& 0%%); add("b);

$ere is the output: C:'ne(pr#rm)*a"ac 1crollbar2emo.*a"a C:'ne(pr#rm)applet"ie(er 1crollbar2emo.html

A scrollable text displa+ ob*ect with one row of characters is known as the TextField. In the example given below* shown a textfield in the applet by creating its ??????? textfield.shtml ob#ect.

%%%%%%% ob#ect. AAAAAAA !.0


import java.awt.*; import java.applet.Applet; public class Te2t:ield5e6o extends Applet{ public void init(){ Te2t:ield t; = new Te2t:ield("Type in t*e bo2"); add(t;);

$ere is the output: C:'ne(pr#rm)*a"ac TextField2emo.*a"a C:'ne(pr#rm)applet"ie(er TextField2emo.html

The common methods of AWT components are as follow 3 #etLocation,- 4 This method is used to get position of the component* as a Coint. The usage of the method is shown below.

5oint p 6 someComponent.#etLocation,-7 int x 6 p.x7 int + 6 p.+7 6ne point to note here is that if you are working on Java 0 Clatform then you need not to create a new point ob#ect. The x and y parts of the location can be easily accessed by using #et8,- and #et9,-. It is always efficient to use #et8,- and #et9,- methods. For example* int x 6 someComponent.#et8,-7 int + 6 someComponent.#et9,-7 :. #etLocation&n1creen,- 4 This method is used to get the position of the upper;left corner of the screen of the component* as a Coint. The usage of the method is shown below. 5oint p 6 someComponent.#etLocation&n1creen,-7 int x 6 p.x7 int + 6 p.+7 It is always advisable to use #etLocation,-7 method if you are working on Java 0 platform. ;. #etBounds,- 4 This method is used to get the current bounding /ectangle of component. The usage of the method is shown below. Rectan#le r 6 someComponent.#etBounds,-7 int hei#ht 6 r.hei#ht7 int (idth 6 r.(idth7 int x 6 r.x7 int + 6 r.+7 6ne point to note here is that if you need a /ectangle ob#ect then the efficient way is to use #et8,-! #et9,-! #et idth,-! and #et$ei#ht,- methods while working on Java 0 platform. <. #et1i0e,- 4 This method is used to get the current siFe of component* as a 7imension. The usage of the method is shown below. 2imension d 6 someComponent.#et1i0e,-7 int hei#ht 6 d.hei#ht7 int (idth 6 d.(idth7 Again* it is always advisable to use #et idth,- and #et$ei#ht,- methods to directly access the width and height while working on Java 0 platform. 2ou can also use #et1i0e,- if you re1uire a 7imension ob#ect. For -xample*

int hei#ht 6 someComponent.#et$ei#ht,-7 int (idth 6 someComponent.#et idth,-7 =. setBack#round,Color->setFore#round,Color- 4 This method is used to change the backgroundBforeground colors of the component. ?. setFont,Font- 4 This method is used to change the font of text within a component. @. setAisible,boolean- 4 This method is used for the visibility state of the component. The component appears on the screen if setAisible,- is set to true and if its set to .alse then the component will not appear on the screen. Furthermore* if we mark the component as not visible then the component will disappear while reserving its space in the 9DI. B. setEnabled,boolean- 4 This method is used to toggle the state of the component. The component will appear if set to true and it will also react to the user. 6. the contrary* if set to .alse then the component will not appear hence no user interaction will be there. As discussed earlier a container is a component that can be nested. The most widely used Canel is the ,lass Canel which can be extended further to partition 9DIs. There is a Canel which is used for running the programs. This Canel is known as ,lass Applet which is used for running the programs within the 3rowser. Common Container %ethods All the subclasses of the ,ontainer class inherit the behavior of more than := common methods of ,ontainer. These subclasses of the container mostly override the method of component. "ome of the methods of container which are most widely used are as follow #etComponents,-7 add,-7 #etComponentCount,-7 #etComponent,int-7 1croll5ane The "crollCane container provides an automatic scrolling of any larger component which was introduced with the !.! release of the Ca"a Runtime En"ironment ,CRE-. Any image which is bigger in siFe for the display area or a bunch of spreadsheet cells is considered as a large ob#ect. >oreover there is no La+out%ana#er for a 1croll5ane because only a single ob#ect exists within it. @owever* the mechanism of -vent @andling is being managed for scrolling. The example below shows the "crollpane. This scrollpane demonstrates the scrolling of the large image. In the program code below* first of all we have created a scrollpane by creating its ob#ect* then we have passed the parameter of image in it. We have also set the border layout as centre* as shown.
import java.awt.*;

import java.applet.*; class S+)ollpane extends !o6ponent { private I6a,e i6a,e; public S+)ollpane(I6a,e 6) { i6a,e = 6; public void paint(()ap*i+" ,) { if (i6a,e <= null) ,.d)awI6a,e(i6a,e& %& %& this);

public class S+)ollin,I6a,e5e6o extends Applet { public void init() { "et3ayout(new Bo)de)3ayout()); S+)oll=ane S! = new S+)oll=ane(S+)oll=ane.S!->33BA-S?A3@AAS); I6a,e 6, = ,etI6a,e(,et!odeBa"e()& "+ute9puppy.,i;"); S!.add(new S+)ollpane(6,)); add(S!& Bo)de)3ayout.!8BT8-);

$ere is the output: C:'ne(pr#rm)*a"ac 1crollin#Dma#e2emo.*a"a C:'ne(pr#rm)applet"ie(er 1crollin#Dma#e2emo.html Dntroduction There are many types of events that are generated by your AWT Application. These events are used to make the application more effective and efficient. 9enerally* there are twelve types of event are used in Java AWT. These are as follows !. Action-vent 0. Ad#ustment-vent 5. ,omponent-vent 8. ,ontainer-vent :. Focus-vent <. Input-vent G. Item-vent E. Hey-vent I. >ouse-vent !=. Caint-vent !!. Text-vent !0. Window-vent These are twelve mentioned events are explained as follows

!. ActionE"ent: This is the ActionE"ent class extends from the A TE"ent class. It indicates the component;defined events occurred i.e. the event generated by the component like 3utton* ,heckboxes etc. The generated event is passed to every -vent+istener ob#ects that receives such types of events using the addAction+istener&( method of the ob#ect. 0. Ad*ustmentE"ent: This is the Ad*ustmentE"ent class extends from the AWT-vent class. When the Ad#ustable Jalue is changed then the event is generated. 5. ComponentE"ent: ComponentE"ent class also extends from the AWT-vent class. This class creates the low;level event which indicates if the ob#ect moved* changed and it4s states &visibility of the ob#ect(. This class only performs the notification about the state of the ob#ect. The ,omponent-vent class performs like root class for other component;level events. 8. ContainerE"ent: The ContainerE"ent class extends from the ComponentE"ent class. This is a low;level event which is generated when container4s contents changes because of addition or removal of a components. :. FocusE"ent: The FocusE"ent class also extends from the ,omponent-vent class. This class indicates about the focus where the focus has gained or lost by the ob#ect. The generated event is passed to every ob#ects that is registered to receive such type of events using the addFocus+istener&( method of the ob#ect. <. DnputE"ent: The DnputE"ent class also extends from the ,omponent-vent class. This event class handles all the component;level input events. This class acts as a root class for all component;level input events. G. DtemE"ent: The DtemE"ent class extends from the AWT-vent class. The Item-vent class handles all the indication about the selection of the ob#ect i.e. whether selected or not. The generated event is passed to every Item+istener ob#ects that is registered to receive such types of event using the addItem+istener&( method of the ob#ect. E. Ee+E"ent: Ee+E"ent class extends from the Input-vent class. The Hey-vent class handles all the indication related to the key operation in the application if you press any key for any purposes of the ob#ect then the generated event gives the information about the pressed key. This type of events check whether the pressed key left key or right key* 4A4 or 4a4 etc. I. %ouseE"ent: %ouseE"ent class also extends from the DnputE"ent class. The >ouse-vent class handle all events generated during the mouse operation for the ob#ect. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right.

!=. 5aintE"ent: 5aintE"ent class also extends from the ,omponent-vent class. The Caint-vent class only ensures that the paint&( or update&( are serialiFed along with the other events delivered from the event 1ueue. !!. TextE"ent: TextE"ent class extends from the AWT-vent class. Text-vent is generated when the text of the ob#ect is changed. The generated events are passed to every Text+istener ob#ect which is registered to receive such type of events using the addText+istener&( method of the ob#ect. !0. indo(E"ent : indo(E"ent class extends from the ,omponent-vent class. If the window or the frame of your application is changed &6pened* closed* activated* deactivated or any other events are generated(* Window-vent is generated.

In this section* you will learn how to handle e"ents in Ca"a a(t. E"ents are the integral part of the #ava platform. 2ou can see the concepts related to the event handling through the example and use methods through which you can implement the event driven application. For any e"ent to occur* the ob*ects registers themselves as listeners. .o event takes place if there is no listener i.e. nothing happens when an event takes place if there is no listener. .o matter how many listeners there are* each and every listener is capable of processing an event. For example* a 1impleButtonE"ent applet registers itself as the listener for the button4s action events that creates a 3utton instance. ActionListener can be implemented by any ,lass including Applet. 6ne point to remember here is that all the listeners are always notified. >oreover* you can also call A TE"ent.consume,- method whenever you don4t want an event to be processed further. There is another method which is used by a listener to check for the consumption. The method is isConsumed,- method. The processing of the events gets stopped with the consumption of the events by the system once a listener is notified. ,onsumption only works for DnputE"ent and its subclasses. >oreover* if you don4t want any input from the user through keyboard then you can use consume,- method for the Ee+E"ent. The step by step procedure of -vent handling is as follow !. When anything interesting happens then the subclasses of A TE"ent are generated by the component. 0. Any class can act like a +istener class permitted by the -vent sources. For example* addActionListener,- method is used for any action to be performed* where Action is the event type. There is another method by which you can remo"e the listener class which is remo"e888Listener,- method! where KKK is the event type. 5. A listener type has to be implemented for an event handling such as ActionListener.

8. There are some special type of listener types as well for which you need to implement multiple methods like ke+ E"ents. There are three methods which are re1uired to be implemented for Hey events and to register them i.e. one .or ke+ release! ke+ t+ped and one .or ke+ press. There are some special classes as well which are known as adapters that are used to implement the listener inter.aces and stub out all the methods. these adapter classes can be sub classed and and can o"erride the necessar+ method. A TE"ent

>ost of the times every event;type has Listener inter.ace as E"ents subclass the A TE"ent class. @owever* 5aintE"ent and DnputE"ent don4t have the +istener interface because only the paint,- method can be overriden with 5aintE"ent etc. Lo(4le"el E"ents A lo(4le"el input or (indo( operation is represented by the Lo(4le"el e"ents. Types of +ow;level events are mouse mo"ement! (indo( openin#! a ke+ press etc. For example* three events are generated by typing the letter 4A4 on the Heyboard one for releasing* one for pressing* and one for typing. The different type of lo(4le"el e"ents and operations that #enerate each e"ent are show below in the form of a table. Dsed for 9ettingBlosing focus. Dsed for entering* exiting* clicking* %ouseE"ent dragging* moving* pressing* or releasing. ContainerE"ent Dsed for AddingBremoving component. Dsed for releasing* pressing* or typing Ee+E"ent &both( a key. Dsed for opening* deactivating* closing* indo(E"ent Iconifying* deiconifying* really closed. ComponentE"ent Dsed for moving* resiFing* hiding* showing. 1emantic E"ents The interaction with 9DI component is represented by the 1emantic e"ents like changing the text of a text field* selecting a button etc. The different events generated by different components is shown below. DtemE"ent ActionE"ent TextE"ent Ad*ustmentE"ent Dsed for state changed. Dsed for do the command. Dsed for text changed. Dsed for value ad#usted. FocusE"ent

E"ent 1ources If a component is an event source for something then the same happens with its subclasses. The different event sources are represented by the following table. Lo(4Le"el E"ents Window ,ontainer

,omponent

Window+istener ,ontainer+istener ,omponent+istener Focus+istener Hey+istener >ouse+istener >ouse>otion+istener

1emantic E"ents "crollbar TextArea TextField 3utton +ist >enuItem TextField ,hoice ,heckbox ,heckbox ,heckbox>enuItem +ist Ad#ustment+istener Text+istener

Action+istener

Item+istener

E"ent Listeners -very listener inter.ace has at least one event type. >oreover* it also contains a method for each type of event the event class incorporates. For example as discussed earlier* the Ee+Listener has three methods* one for each type of event that the Ee+E"ent has ke+T+ped,-! ke+5ressed,-! and ke+Released,-. The +istener interfaces and their methods are as follow Dnter.ace Window+istener %ethods windowActivated&Window-vent e( window7eiconified&Window-vent e( window6pened&Window-vent e( window,losed&Window-vent e(

window,losing&Window-vent e( windowIconified&Window-vent e( window7eactivated&Window-vent e( Action+istener actionCerformed&Action-vent e( ad#ustmentJalue,hanged&Ad#ustment-vent Ad#ustment+istener e( mouse,licked&>ouse-vent e( mouse-ntered&>ouse-vent e( >ouse+istener mouse-xited&>ouse-vent e( mouseCressed&>ouse-vent e( mouse/eleased&>ouse-vent e( focus9ained&Focus-vent e( Focus+istener focus+ost&Focus-vent e( Item+istener item"tate,hanged&Item-vent e( Hey+istener key/eleased&Hey-vent e( keyTyped&Hey-vent e( keyCressed&Hey-vent e( component@idden&,omponent-vent e( component>oved&,omponent-vent e( ,omponent+istener component"hown&,omponent-vent e( component/esiFed&,omponent-vent e( >ouse>otion+istener mouse>oved&>ouse-vent e( mouse7ragged&>ouse-vent e( Text+istener textJalue,hanged&Text-vent e( ,ontainer+isten er componentAdded&,ontainer-vent e( component/emoved&,ontainer-vent e(

You might also like