1. QUESTION BANK
UNIT –I
Q.1 Write a Short note on “Event Listeners”?Explain the workingwith code specification.
Ans: 1. The Event listener represent the interfacesresponsibleto handleevents.Java providesusvariousEvent
listener classes
2. It is also known aseventhandler.Listeneris responsibleforgenerating responseto an event.
3. Fromjava implementation pointof view the listener is also an object.Listener waits until it receives an
event.Once theevent is received , the listener processthe event and then returns.
Code specification:
importjava.awt.*;
importjava.awt.event.*;//Using AWTeventsand listener interfaces
public class HELLO extendsFrameimplementsWindowListener{
HELLO() {
setLayout(new FlowLayout());
Button btnCount=newButton("ok");
add(btnCount);
addWindowListener(this);
setTitle("WindowEventDemo");
setSize(250, 100);
setVisible(true);
}
public static void main(String[] args){
HELLO h= newHELLO ();
}
public void windowClosing(WindowEvente) {
System.exit(0); //Terminatethe program
}
public void windowOpened(WindowEvente) { }
public void windowClosed(WindowEvente) { }
public void windowIconified(WindowEvente) { }
public void windowDeiconified(WindowEvente) { }
public void windowActivated(WindowEvente) { }
public void windowDeactivated(WindowEvente) { }
2. }
Q.2 How does AWTcreate radio buttons ? Explain with syntax & code specification.
Ans: Radiobuttons givea more userfriendly environmentwhen theuserhasto select onlyone option
amongmany.
There is no radio button classin java.awt package.
AWT usesthe Checkbox classforboth check boxesand radio buttons.
Radio buttonsarea group of checkboxesgrouped asoneunit.In the unit,if anotherradio button is
selected, theearlier gets automatically deselected.
Becauseradio button isa check box,all the methodsillustrated in "Java AWTCheckbox" can beused
here.
To create a radio button,you need to create check boxes,and add themto a checkbox group.
Code specification:
importjava.awt.*;
importjava.awt.event.*;
public class Demo3extendsFrameimplementsItemListener{
Label stLabel;
Demo3(){
setLayout(newFlowLayout());
CheckboxGroup fruitGroup=newCheckboxGroup();
Checkbox chkApple=new Checkbox("Apple",fruitGroup,true);
Checkbox chkMango =newCheckbox("Mango",fruitGroup,false);
Checkbox chkPeer= newCheckbox("Peer",fruitGroup,false);
add(chkApple);
add(chkMango);
add(chkPeer);
stLabel=newLabel();
add(stLabel);
chkApple.addItemListener(this);
chkMango.addItemListener(this);
chkPeer.addItemListener(this);
setTitle("WindowEventDemo");
setSize(250, 100);
setVisible(true);
}
public static void main(String[] args){
Demo3d=new Demo3();
}
public void itemStateChanged(ItemEvente) {
stLabel.setText(e.getItem()
+" Checkbox:"
+ (e.getStateChange()==1?"checked":"unchecked"));
}
}
3. Q.3 What is the defaultlayout of the frame?Explain the same.
Ans: 1. A containerhasa so-called layoutmanagerto arrangeitscomponents.Thelayoutmanagersprovidea
level of abstraction to map youruserinterface on all windowing systems,so thatthelayoutcan be
platform-independent.
2. AWT providesthefollowing layoutmanagers(in
packagejava.awt): FlowLayout, GridLayout, BorderLayout, GridBagLayout, BoxLayout, CardLayout,and
others.
3. DefaultLayoutof the frameis Border Layout
4. In java.awt.BorderLayout, thecontaineris divided into 5 zones:EAST, WEST, SOUTH, NORTH,
and CENTER.
5. Constructor:
public BorderLayout();
public BorderLayout(inthgap,intvgap);
6. Code Specification:
importjava.awt.*;
public class Demo extendsFrame{
Demo() {
setLayout(newBorderLayout(3,3));
ButtonbtnNorth= newButton("NORTH");
add(btnNorth, BorderLayout.NORTH);
ButtonbtnSouth= newButton("SOUTH");
add(btnSouth,BorderLayout.SOUTH);
ButtonbtnCenter= newButton("CENTER");
add(btnCenter,BorderLayout.CENTER);
ButtonbtnEast = newButton("EAST");
add(btnEast,BorderLayout.EAST);
ButtonbtnWest= newButton("WEST");
add(btnWest,BorderLayout.WEST);
setTitle("BorderLayoutDemo");//"this"Frame setstitle
setSize(280,150); // "this"Frame setsinitial size
setVisible(true); // "this"Frame shows
}
public static void main(String[] args) {
Demo d=new Demo();
}
}
4. Q.4 Write a java AWT program that creates the followingGUI( considerthe window closingevent)
Login Screen
Userid:
Passwd:
Ans:
importjava.awt.*;
public class LoginfrmextendsFrame implementsWindowListener{
Loginfrm(){
setLayout(new FlowLayout());
addWindowListener(this)
Label a = new Label("Userid :");
add(a);
TextField tf = newTextField("EnterUR name",10);
tf.setEditable(true);
add(tf);
Label b = newLabel("Passwd :");
add(b);
TextField tf1 = new TextField("EnterURname",5);
tf.setEditable(true);
add(tf1);
Button btn= new Button("SUBMIT");
add(btn);
Button btn1= newButton("CANCEL");
add(btn1);
setTitle("DemoForm");
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args) {
Loginfrm d=new Loginfrm();
}
public void windowClosing(WindowEvente) {
System.exit(0); //Terminatethe program
}
public void windowOpened(WindowEvente) { }
public void windowClosed(WindowEvente) { }
public void windowIconified(WindowEvente) { }
CANCELSUBMIT
5. public void windowDeiconified(WindowEvente) { }
public void windowActivated(WindowEvente) { }
public void windowDeactivated(WindowEvente) { } }
Q.5 List differenttypesof layout manager ? ExplainGridLayout.
Ans: Sr.
No.
LayoutManager & Description
1
BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and
center.
2
CardLayout
The CardLayout object treats each component in the container as a card. Onlyone card is
visible at a time.
3
FlowLayout
The FlowLayout is the default layout.It layouts the components in a directionalflow.
4
GridLayout
The GridLayout manages the components in form of a rectangular grid.
5
GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout alignsthe
component vertically,horizontallyor along their baseline without requiringthe components of
same size.
GridLayout:
A GridLayoutobjectplacescomponentsin a grid of cells. Each componenttakesallthe availablespace within its
cell, and each cell is exactly the samesize. If the GridLayoutDemo window isresized, the GridLayoutobject
changesthecell size so thatthe cells are as large as possible,given the spaceavailableto the container.
GridLayoutDesign :
Q.6 Compare and contrast AWT& Swings
Ans: AWT componentsarecalled HeavyWeight componentand Swingsarecalled ligth weightcomponent
becauseswing componentssitson thetop of AWT componentsand do thework.
Swingscomponentsaremadein purely java and they are platformindependentwhereasAWT
compoentsareplatformdependent.
We can havedifferentlookand feel in Swing whereasthis featureis notsupported in AWT.
Swing hasmany advanced featureslikeJTabel,Jtabbed pane which isnot availablein awt
Q.7. Explainthe java EventDelegationmodel
Ans:
EventHandlingisthe mechanismthatcontrolsthe eventanddecideswhatshouldhappenif anevent
6. occurs. Thismechanismhas the code whichisknownas eventhandlerthatisexecuted whenanevent
occurs java Usesthe DelegationEventModel to handle the events. Thismodel definesthe standard
mechanismtogenerate andhandle the events.
The DelegationEventModel has the followingkeyparticipants namely:
Source - The source is an objectonwhicheventoccurs.Source isresponsibleforprovidinginformation
of the occurredeventtoit's handler.Javaprovide aswithclassesforsource object.
Listener- It isalsoknownas eventhandler.Listenerisresponsible forgeneratingresponse toanevent.
From javaimplementationpointof view the listenerisalsoanobject.Listenerwaitsuntilitreceivesan
event.Once the eventisreceived,the listenerprocessthe event andthenreturns.
The benefitof thisapproach isthat
The user interface logiciscompletelyseparatedfromthe logicthatgeneratesthe event.
The user interface elementisable todelegate the processingof aneventtothe separate piece of
code.
In thismodel ,Listenerneedsto be registeredwiththe source objectsothat the listenercanreceive
the eventnotification.
Thisis an efficientwayof handlingthe eventbecause the eventnotificationsare sentonlytothose
listenerthatwanttoreceive them.
Q.8. What are adapter classes? Whatare innerclasses? Explain withexamples.
Ans: Adapter Classes:
An adapterclass providesthedefaultimplementation of all methodsin an eventlistener interface.Adapter
classesare very usefulwhen you wantto processonly few of the eventsthatare handled by a particularevent
listenerinterface.You can definea new classby extending oneof theadapterclasses and implement only those
eventsrelevantto you.
Exampleof Adapter class:Here's a mouseadapterthatbeeps when themouseis clicked
importjava.awt.*;
importjava.awt.event.*;
public class MouseBeeperextendsMouseAdapter
{
public void mouseClicked(MouseEventevt)
{
Toolkit.getDefaultToolkit().beep();
}
}
By subclassing MouseAdapterratherthan implementing MouseListenerdirectly,you avoid having to writethe
methodsyou don'tactually need.You only overridethosethatyou plan to actually implement.
Inner Class:
Innerclasses are classwithin Class.Innerclass instancehasspecial relationship with Outer class.This special
relationship givesinner class accessto memberof outerclass asif they are thepart of outerclass.
Exampleof Inner class:
importjava.awt.Frame;
importjava.awt.event.WindowAdapter;
importjava.awt.event.WindowEvent;
7. public class FrameClosing3extendsFrame
{
publicFrameClosing3()
{
addWindowListener(newWindowAdapter()
{
public void windowClosing(WindowEvente)
{ System.exit(0);}
}
);
setTitle("Frame closing Style 3");
setSize(300, 300);
setVisible(true);
}
public static void main(String args[])
{
new FrameClosing3();
}
}
Q.9 What are differentoperationsthat can be carried out on frame windows?
Ans: A Frameis a top-levelwindowwitha title and a border.The size of the frameincludesany area designated for
the border.The dimensionsof theborderarea may be obtained using thegetInsetsmethod,however,since
these dimensionsareplatform-dependent,a valid insetsvaluecannotbe obtained untilthe frameis made
displayableby either calling packor show.The defaultlayoutfora frameis BorderLayout.
Operationsassociated withframe:
1. Add(Componentobj)
2. setLayout(LayoutManagerObject)
3. setSize(int,int)
4. setSize(Dimension ob)
5. setVisible(Boolean)
6. pack()/show()
Example:
importjava.awt.*;
public class NewMain extendsFrame{
NewMain(){
setLayout(new BorderLayout(3,3));
Button btnNorth=newButton("NORTH");
add(btnNorth,BorderLayout.NORTH);
Button btnSouth=newButton("SOUTH");
add(btnSouth,BorderLayout.SOUTH);
Button btnCenter= newButton("CENTER");
add(btnCenter,BorderLayout.CENTER);
Button btnEast= newButton("EAST");
add(btnEast,BorderLayout.EAST);
Button btnWest= new Button("WEST");
add(btnWest,BorderLayout.WEST);