[Go to site: main page, start]

0% found this document useful (0 votes)
7 views60 pages

Java AWT Controls and Components Guide

The document provides an overview of Java AWT (Abstract Window Toolkit), detailing its purpose for developing GUI applications and its class hierarchy. It explains the characteristics of AWT components, including their heavyweight nature and platform dependency, and introduces various controls such as labels, buttons, and checkboxes. Additionally, it includes examples of how to implement these controls in Java applications.

Uploaded by

Sushma Mishra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views60 pages

Java AWT Controls and Components Guide

The document provides an overview of Java AWT (Abstract Window Toolkit), detailing its purpose for developing GUI applications and its class hierarchy. It explains the characteristics of AWT components, including their heavyweight nature and platform dependency, and introduces various controls such as labels, buttons, and checkboxes. Additionally, it includes examples of how to implement these controls in Java applications.

Uploaded by

Sushma Mishra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE -4 CHAPTER NO– 06

AWT CONTROLS
Lecture-30

Learning Objectives:
The students will be able to understand
6.1 AWT class Hierarchy

Introduction :

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
[Link] AWT components are platform-dependent i.e. components are displayed according to the view
ofoperating system. AWT is heavyweight i.e. its components are using the resources of OS.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,RadioButton,
CheckBox, Choice, List etc.
What is called AWT ?
AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI
(Graphical User Interface) or window-based applications in Java. It was developed by Sun
Microsystem In 1995.
What is the awt with examples in java ?
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java. Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
Why AWT is abstract ?
AWT is the short form for “Abstract Window Toolkit”. AWT is an API for creating GUI
applications in Java. It is a platform-dependent framework i.e. the GUI components belonging to
AWT are not the same across all platforms.

Why we use AWT in java ?


awt. Provides the classes necessary to create an applet and the classes an applet uses to communicate
with its applet context. Contains all of the classes for creating user interfaces and for painting
graphics and images.
Why AWT componebts are heavy weight ?
AWT components are heavyweight components, because they rely on the local platform's
windowing system to determine their functionality and their look-and-feel. Several Swing
components are heavyweight components.
Why AWT is called peer component ?
Each GUI component that AWT provides has a peer. The peer is the implementation of that
component in the native environment. For example, the Choice component in AWT corresponds to
some native object that lets the user select one or more items from a list.
What is java AWT package ?
The AWT package contains several layout manager classes and an interface for building your own
layout manager. See Container and LayoutManager for more information. Each Component object is
limited in its maximum size and its location because the values are stored as an integer.
What is AWTException in java ?
AWTException is a generic exception that can be thrown when an exceptional condition has
occurred within AWT. None of the AWT classes throw this. If you subclass any of the AWT classes,
you can throw an AWTException to indicate a problem.
What is import java AWT?
import java. awt. Graphics means that the Graphics class in the java. awt package is made known
to the current class. import java.

6.1.1 Java AWT Hierarchy


What is the use of AWT controls ?
Java AWT controls are the controls that are used to design graphical user interfaces or web
applications. To make an effective GUI, Java provides java.

How many classes are there in AWT ?


The AWT provides nine basic non-container component classes from which a user interface may
be constructed. (Of course, new component classes may be derived from any of these or from class
Component itself.) These nine classes are class Button, Canvas, Checkbox, Choice, Label, List,
Scrollbar, TextArea, and TextField.
The hierarchy of Java AWT classes are given below.

Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.


public void setSize(int width,int
height) sets the size (width and
height) of thecomponent.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean changes the visibility of the component,


status) by default false.
MODULE -4 CHAPTER NO– 06
AWT CONTROLS
Lecture-31

Learning Objectives:
The students will be able to understand
6.2 User Interface Components

6.2.1 Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)

o By creating the object of Frame class (association)

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
1. import [Link].*;

2. class First extends Frame{

3. First(){

4. Button b=new Button("click me");

5. [Link](30,100,80,30);// setting button position

6. add(b);//adding button into frame

7. setSize(300,300);//frame size 300 width and 300 height

8. setLayout(null);//no layout manager

9. setVisible(true);//now frame will be visible, by default not visible

10. }

11. public static void main(String args[]){

12. First f=new First();13. }}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.

1. import [Link].*;

2. class First2{

3. First2(){

4. Frame f=new Frame();

5. Button b=new Button("click me");

6. 6. [Link](30,50,80,30);

7. [Link](b);

8. [Link](300,300);

9. [Link](null);

10. [Link](true);

11. }

12. public static void main(String args[]){

13. First2 f=new First2();

14. 14. }}
Examples of GUI based Applications

Following are some of the examples for GUI based applications.

 Automated Teller Machine (ATM)

 Airline Ticketing System

 Information Kiosks at railway stations

 Mobile Applications

 Navigation Systems

Examples of Label component class in java

import [Link].*;

import [Link].*;

/*<applet code=”[Link]” width=500 height=600>

</applet>*/

Public class LabelDemo extends Applet

Public void init()

setBackground([Link]);

SetForeground([Link]);

Label l1=new Label(“Branch”);

Label l2=new Label(“College”);

add(l1);

add(l2);
}

Public paint(graphics g)

[Link](“LabelDemo”,100,100);

import [Link].*;

import [Link].*;

/*<applet code=”[Link]” width=500 height=600>

</applet>*/

Public class ButtonDemo extends Applet implements ActionListener

Public void init()

Button b1=new Button(“Red”);

Button b2=new Button(“Blue”);

Button b3=new Button(“Green”);

add(b1);

add(b2);

add(b3);

[Link](this);

[Link](this);

[Link](this);

Public paint(graphics g)

[Link](“ButtonDemo”,100,100);
}

Public void ActionPerformed(ActionEvent ae)

String str=[Link]();

if([Link](“Red”))

setBackground([Link]);

else if([Link](“Blue”))

setBackground([Link]);

else

setBackground([Link]);

import [Link].*;

import [Link].*;

import [Link].*;

Checkbox

/*<apple code=”[Link]” width=500 height=600>

</applet>*/

Public class CheckboxDemo extends Applet

Public void init()

setBackground([Link]);

SetForeground([Link]);

Checkbox c1=new Checkbox(“Cricket”);

Checkbox c2=new Checkbox(“Tennis”);

Checkbox c3=new Checkbox(“Football”);


Checkbox c4=new Checkbox(“Bamiton”);

add(c1);

add(c2);

add(c3);

add(c4);

Public paint(graphics g)

[Link](“CheckBoxDemo”,100,100);

CheckboxGroup

/*<apple code=”[Link]” width=500 height=600>

</applet>*/

Public class CheckboxGroupDemo extends Applet

Public void init()

setBackground([Link]);

SetForeground([Link]);

CheckboxGroup cbg=new CheckboxGroup();

Checkbox c1=new Checkbox(“CSE”,cbg,true);

Checkbox c2=new Checkbox(“ECE”,cbg,true);

Checkbox c3=new Checkbox(“CE”,cbg,false);

Checkbox c4=new Checkbox(“EEE”,cbg,false);

add(c1);

add(c2);
add(c3);

add(c4);

Public paint(graphics g)

[Link](“Branches”,100,100);

}
The AWT supports the following types of controls:
■ Labels
■ Push buttons
■ Check boxes
■ Choice lists
■ Lists
■ Scroll bars
■ Text editing
These controls are subclasses of Component.
Adding and Removing Controls:
To include a control in a window, you must add it to the window. To do this, you must first create an
instance of the desired control and then add it to a window by calling add( ),which is defined by
Container. The add( ) method has several forms. The following form is the one that is used for the first
part of this chapter:
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add.
Sometimes you will want to remove a control from a window when the control is no longer needed. To
do this, call remove( ). This method is also defined by [Link] has this general form:
void remove(Component obj)
Here, obj is a reference to the control you want to remove.
MODULE -4 CHAPTER NO– 06
AWT CONTROLS
Lecture-32

Learning Objectives:
The students will be able to understand
6.3 AWT Controls

6.3.1 Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it
displays. Labels are passive controls that do not support any interaction with the user. Label defines the
following constructors:
Label() Label(String str)
Label(String str, int how)
The first version creates a blank label. The second version creates a label that contains the string
specified by str. This string is left-justified. The third version creates a label that contains the string
specified by str using the alignment specified by how. The value of how must be one of these three
constants: [Link], [Link], or [Link].
You can set or change the text in a label by using the setText( ) method. You can obtain the current
label by calling getText( ). These methods are shown here:

void setText(String str) String


getText( )
// Demonstrate Labels import
[Link].*; import [Link].*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>*/
public class LabelDemo extends Applet
{
public void init()
{
Label Label("One"); Label two =
new Label("Two"); Label three = new
Label("Three");
// add labels to applet window add(one);
add(two); add(three);
}
}
Output:

6.3.2 Using Buttons


The most widely used control is the push button. A push button is a component that contains a label and
that generates an event when it is pressed. Push buttons are objects of type Button. Button defines these
two constructors:
Button( ) Button(String str)
The first version creates an empty button. The second creates a button that contains str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by
calling getLabel( ). These methods are as follows:

void setLabel(String str) String


getLabel( )
Here, str becomes the new label for the button.

Handling Buttons:
Each time a button is pressed,an ActionEvent is generated. This is sent to any listeners that previously
registered an interest in receiving action event notifications from that component. Each listener
implements the ActionListener interface. That interface defines the actionPerformed( ) method, which
is called when an event occurs. An ActionEvent object is supplied as the argument to this method.

// Demonstrate Buttons import


[Link].*; import [Link].*;
import [Link].*;
/*<applet code="ButtonDemo" width=250 height=150>
</applet>*/
public class ButtonDemo extends Applet implements ActionListener
{
String msg = ""; Button yes, no,
maybe;public void init()
{
yes = new Button("Yes"); no = new
Button("No");
maybe = new Button("Undecided");add(yes);
add(no); add(maybe);
[Link](this); [Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{

String str = [Link]();


if([Link]("Yes"))
{
msg = "You pressed Yes.";
}
else if([Link]("No"))
{
msg = "You pressed No.";
}
else
{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
[Link](msg, 6, 100);
}
}

Output:
6.3.3 Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a 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 presents.
Checkbox supports these constructors:
Checkbox( ) Checkbox(String
str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)

The first form creates a check box whose label is initially blank. The state of the check box is unchecked.
The second form creates a check box whose label is specified by str. The state of the check box is
unchecked. The third form allows you to set the initial state of the check box. If on is true, the check box
is initially checked; otherwise, it is cleared. The fourth and fifth forms create a check box whose label is
specified by str and whose group is specified by cbGroup. If this check box is not part of a group, then
cbGroup must be null. (Check box groups are described in the next section.) The value of on determines
the initial state of the check box.
To retrieve the current state of a check box, call getState( ). To set its state, call setState( ). You can
obtain the current label associated with a check box by calling getLabel( ). To set the label, call
setLabel( ). These methods are as follows:
boolean getState( )
void setState(boolean on) String
getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed in str
becomes the new label associated with the invoking check box.

Handling Check Boxes:


Each time a check box is selected or deselected, an item event is generated. This is sent to any
listeners that previously registered an interest in receiving item event notifications from that component.
Each listener implements the ItemListener interface. That interface defines the itemStateChanged( )
method. An ItemEvent object is supplied as the argument to this method. It contains information about
the event.
// Demonstrate check boxes. import
[Link].*;
import [Link].*; import
[Link].*;
/*<applet code="CheckboxDemo" width=250 height=200>
</applet>*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox Win98, winNT, solaris, mac; public
void init()
{
Win98 = new Checkbox("Windows 98/XP", null, true);winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); add(Win98);
add(winNT);
add(solaris);add(mac);
[Link](this);
[Link](this);
[Link](this);

[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

public void paint(Graphics g)


{
msg = "Current state: "; [Link](msg, 6,
80);
msg = " Windows 98/XP: " + [Link]();
[Link](msg, 6, 100);
msg = " Windows NT/2000: " + [Link]();
[Link](msg, 6, 120);
msg = " Solaris: " + [Link]();[Link](msg, 6, 140);
msg = " MacOS: " + [Link]();
[Link](msg, 6, 160);
}}Output:

6.3.4 CheckboxGroup:
It is possible to create a set of mutually exclusive check boxes in which one and only one check box in
the group can be checked at any one time. These check boxes are often called radio buttons.

Check box groups are objects of type CheckboxGroup. Only the default constructor is defined, which
creates an empty [Link] can determine which check box in a group is currently selected by calling
getSelectedCheckbox( ). You can set a check box by calling setSelectedCheckbox( ). These methods
are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Here, which is the check box that you want to be selected.

// Demonstrate check box group. import


[Link].*;
import [Link].*; import
[Link].*;
/*<applet code="CBGroup" width=250 height=200>
</applet>*/
public class CBGroup extends Applet implements ItemListener
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init()
{
setBackground([Link]); cbg = new
CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true); winNT =
new Checkbox("Windows NT/2000", cbg, false); solaris = new
Checkbox("Solaris", cbg, false);
mac = new Checkbox("MacOS", cbg, false);
add(Win98);
add(winNT);
add(solaris);add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}public void paint(Graphics g)
{
msg = "Current selection: ";
msg += [Link]().getLabel();
[Link](msg, 6, 100);
}}
Output:
MODULE -4 CHAPTER NO– 06
AWT CONTROLS
Lecture-33

Learning Objectives:
The students will be able to understand
6.3 AWT Controls

6.3.5 Choice Controls:

The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. Choice only defines the default constructor,
which creates an empty list. To add a selection to the list, call add( ). It has this general
form:
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the
order inwhich calls to add( ) occur.
To determine which item is currently selected, you may call either getSelectedItem( )
orgetSelectedIndex( ). These methods are shown here:
String getSelectedItem( ) int
getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the
[Link]( ) returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected. To obtain the number of items in the
list, call getItemCount( ). You can set the currently selected item using the select( )
method with either a zero-based integer index or a string that will match a name in the list.
These methods are shown here:
int getItemCount( ) void
select(int index) void
select(String name)
Given an index, you can obtain the name associated with the item at that index by
calling
getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Choice Lists
Each time a choice is selected, an item event is generated. This is sent to any listeners that
previously registered an interest in receiving item event notifications from that
component. Each listener implements the ItemListener interface. That interface defines
the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to
this method.
// Demonstrate Choice
lists. import [Link].*;
import
[Link].*;
import [Link].*;
/*<applet code="ChoiceDemo" width=300 height=180></applet>*/
public class ChoiceDemo extends Applet implements ItemListener
{
Choice os,
browser; String
msg = ""; public
void init()
{
os = new Choice();
browser = new
Choice();
// add items to os list

[Link]("Windows 98/XP");
[Link]("Windows
NT/2000");[Link]("Solaris");
[Link]("MacOS");
// add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer
4.0");
[Link]("Internet Explorer 5.0");
[Link]("Internet Explorer 6.0");
[Link]("Lynx 2.4");
[Link]("Netscape
4.x");
// add choice lists to
windowadd(os);
add(browser);
// register to receive item
events
[Link](this);
[Link](this)
;
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}// Display current selections. public void paint(Graphics g)
{msg = "Current OS: ";
msg += [Link](); [Link](msg, 6, 120); msg = "Current
Browser: ";
msg +=
[Link]();
[Link](msg, 6, 140);
}}
Output:

6.3.6 Using Lists:

The List class provides a compact, multiple-choice, scrolling selection list. It can
also becreated to allow multiple selections. List provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
The first version creates a List control that allows only one item to be selected at any one
time. In the second form, the value of numRows specifies the number of entries in the list
that will always be visible (others can be scrolled into view as needed). In the third form,
if multipleSelect is true, then the user may select two or more items at a time. If it is false,
then only one item may be selected. To add a selection to the list, call add( ). It has the
following two forms:
void add(String name)
Here, name is the name of the item added to the list. This form adds items to the end of
the list.
you can determine which item is currently selected by calling either getSelectedItem( )
or
getSelectedIndex( ). These methods are shown here:
String getSelectedItem( ) int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the
item.
getSelectedIndex( ) returns the index of the item.
For lists that allow multiple selection, you must use either getSelectedItems( )
or
getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( ) int[
] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected
items.
getSelectedIndexes( ) returns an array containing the indexes of the currently selected
items.

You can set the currently selected item by using the select( ) method with a zero-
based integer index. These methods are shown here:
void select(int index)
Given an index, you can obtain the name associated with the item at that index by calling
getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Lists:
To process list events, you will need to implement the ActionListener [Link]
time a List item is double-clicked, an ActionEvent object is generated. Its
getActionCommand( ) method can be used to retrieve the name of the newly selected
item.
// Demonstrate Lists.
import [Link].*;
import
[Link].*;
import [Link].*;
/*<applet code="ListDemo" width=300 height=180>
</applet>*/

public class ListDemo extends Applet implements ActionListener


{
List os,
browser; String
msg = "";
public void
init()
{
os = new List(4, true);
browser = new List(4, false);
// add items to os list
[Link]("Windows 98/XP");
[Link]("Windows NT/2000");
[Link]("Solaris");
[Link]("MacOS");
// add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer 4.0");
[Link]("Internet Explorer 5.0");
[Link]("Internet Explorer 6.0");
[Link]("Lynx 2.4");
[Link](1);
// add lists to window
add(os);
add(browser);
// register to receive action events
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
// Display current
selections. public void
paint(Graphics g)
{
int idx[];
msg = "Current OS: ";
idx =
[Link]();
for(int i=0; i<[Link];
i++)
{
msg += [Link](idx[i]) + " ";
}
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg +=
[Link]();
[Link](msg, 6, 140);
}
}Output:

6.3.7 Managing Scroll Bars:


Scroll bars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. Scrollbar defines the
following constructors:

Scrollbar( ) Scrollbar(int style)


Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
style- [Link] a vertical scroll. style- [Link], the scroll
bar is horizontal. initialValue-initail value of scroll bar. thumbSize-height of thumb. min
and max-minimum and maximum values for the scroll bar.
Methods in Scrollbar:
If you construct a scroll bar by using one of the first two constructors, then you need to
set its parameters by using setValues( ), shown here, before it can be used:
void setValues(int initialValue, int thumbSize, int min, int max)
To obtain the current value of the scroll bar, call getValue( ). It returns the current setting.
Toset the current value, call setValue( ). These methods are as follows:
int getValue( )
void setValue(int newValue)
Here, newValue specifies the new value for the scroll bar.
Handling Scroll Bars:
Type of event generated is [Link] processor or Handle the AdjustmentEvent
implement AdjustmentListener interface ,it has method ,ites general from is as follows.
public void adjustmentValueChanged(AdjustmentEvent ae)

import [Link].*;
import
[Link].*;
import [Link].*;
/*<applet code="SBDemo" width=300 height=200></applet>*/
public class SBDemo extends Applet implements AdjustmentListener,
MouseMotionListener
{
String msg = "";
Scrollbar vertSB,
horzSB; public void
init(){
int width = [Link](getParameter("width"));
int height =
[Link](getParameter("height"));
vertSB = new Scrollbar([Link],0, 1, 0, height);
horzSB = new Scrollbar([Link],0,1, 0,
width); [Link]("width:"+width);
[Link]("height:"+height);
add(vertSB)
;
add(horzSB
);
[Link](this);
[Link](this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
// Update scroll bars to reflect mouse
dragging. public void
mouseDragged(MouseEvent me)
{
int x = [Link](); int y = [Link](); [Link](y); [Link](x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent
me)
{
}
// Display current value of scroll
bars. public void paint(Graphics g)
{
msg = "Vertical: " + [Link]();
msg += ", Horizontal: " +
[Link](); [Link](msg, 6,
160);
// show current mouse drag position
[Link]("*", [Link](),
[Link]());
}}//end

Output:
6.7.8 Using a TextField:
The TextField class implements a single-line text-entry area, usually called an edit
control.
TextField defines the following constructors:
TextField( ) TextField(int numChars)TextField(String str)
TextField(String str, int numChars)
The first version creates a default text field. The second form creates a text field that is
numChars characters wide. The third form initializes the text field with the string
contained in str. The fourth form initializes a text field and sets its width.
To obtain the string currently contained in the text field, call getText( ). To set the text, call
setText( ). These methods are as follows:
String getText( )
void setText(String str)//Here, str is the new string.
MODULE -4 CHAPTER NO– 06

AWT CONTROLS
Lecture-34

Learning Objectives:
The students will be able to understand
6.3 AWT Controls
Handling TextField:
The following example demonstrates you how to process or handle ActionEvent which is
generated from [Link] ENTER key after text is entered in TextField,you can see
output.
import [Link].*;
import
[Link].*;
import [Link].*;

/*<applet code="AwtApp2" width="300" height="300"></applet>*/


public class AwtApp2 extends Applet implements ActionListener
{
TextField tf1;

String s="";

public void init()


{
tf1=new TextField(15);
add(tf1);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
s="entered text:"+[Link]();
repaint();
}

public void paint(Graphics g)


{
[Link](s,75,75);
}}

Output:

6.3.9 Using a TextArea:


Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea. Following is one
of the constructor for TextArea:
TextArea(String str, int numLines, int numChars)
Here, numLines specifies the height, in lines, of the text area, and numChars specifies
itswidth, in characters. Initial text can be specified by str.
//Demonstrate
TextArea. import
[Link].*; import
[Link].*;
/*<applet code="TextAreaDemo" width=300 height=250></applet>*/
public class TextAreaDemo extends Applet
{
public void init()

{
String val = "There are two ways of constructing " + "a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his
telephone.\n" +"That wish has come true,\n" +
"since I no longer know how to use my
telephone.\n\n" + " -Bjarne Stroustrup, AT&T,
(inventor of C++)"; TextArea text = new
TextArea(val, 10, 30);
add(text);
}
}
Output:
6.3.10 Understanding Layout Managers:
All of the components that we have shown so far have been positioned by the default
layout manager.A layout manager automatically arranges your controls within a window
by using some type of algorithm. Each Container object has a layout manager associated
with it. A layout manager is an instance of any class that implements the LayoutManager
interface. The layout manager is set by the setLayout( ) method. The setLayout( )
method has the following general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout
manager.
you will need to determine the shape and position of each component manually,using
the
setBounds( ) method defined by Component.
FlowLayout
FlowLayout is the default layout manager. FlowLayout implements a simple layout
style, which is similar to how words flow in a text editor. Components are laid out from
the upper- left corner, left to right and top to bottom.
Here are the constructors for
FlowLayout:FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels
of space between each component. The second form lets you specify how each line is
aligned. Valid values for how are as follows:

[Link]
[Link]
[Link]
These values specify left, center, and right alignment, respectively. The third form allows
you to specify the horizontal and vertical space left between components in horz and vert,
respectively.
// Use left-aligned flow
layout. import [Link].*;
import
[Link].*;
import [Link].*;
/*<applet code="FlowLayoutDemo" width=250 height=200></applet>*/
public class FlowLayoutDemo extends
Applet implements ItemListener
{
String msg = "";
Checkbox Win98, winNT, solaris,
mac;public void init()
{
// set left-aligned flow layout
setLayout(new FlowLayout([Link]));
Win98 = new Checkbox("Windows 98/XP", null,
true);winNT = new Checkbox("Windows NT/2000");
solaris = new
Checkbox("Solaris"); mac = new
Checkbox("MacOS");
add(Win98);
add(winNT
);
add(solaris)
;add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
// Repaint when status of a check box
changes.
public void itemStateChanged(ItemEvent
ie)
{repaint();}
// Display current state of the check
boxes. public void paint(Graphics g)
{

msg = "Current state: ";


[Link](msg, 6, 80);
msg = " Windows 98/XP: " +
[Link]();[Link](msg, 6, 100);
msg = " Windows NT/2000: " +
[Link]();[Link](msg, 6, 120);
msg = " Solaris: " +
[Link](); [Link](msg,
6, 140);
msg = " Mac: " +
[Link]();
[Link](msg, 6, 160);}}
Output:

BorderLayout:
The BorderLayout class implements a common layout style for top-level windows. It has
four narrow, fixed-width components at the edges and one large area in the center. The
four sides are referred to as north, south, east, and west. The middle area is called the
center. Here are the constructors defined by BorderLayout:
BorderLayout( ) BorderLayout(int
horz, int vert)
The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
[Link] [Link]
[Link] [Link]
[Link]
When adding components, you will use these constants with the following form of
add( ),which is defined by Container:
void add(Component compObj, Object region);

import
[Link].*;
import
[Link].*;
import [Link].*;
/*<applet code="BorderLayoutDemo" width=400 height=200></applet>*/
public class BorderLayoutDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button("This is across the top."),[Link]);
add(new Label("The footer message might go
here."),[Link]); add(new Button("Right"),
[Link]);
add(new Button("Left"), [Link]);
String msg = "The reasonable man adapts " +"himself to the world;\n" +"the
unreasonableone persists in " +
"trying to adapt the world to himself.\n" + "Therefore all progress depends "
+"on theunreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), [Link]);
}}
Output:
MODULE -4 CHAPTER NO– 06

AWT CONTROLS
Lecture-35

Learning Objectives:
The students will be able to understand
6.3 AWT Controls

6.3.11 Menu Bars and Menus:


First create menu bar and then create menu ,next create menu item and then add menu
item to menu ,menu to menu [Link] create a menu bar, first create an instance of
MenuBar. This class only defines the default constructor. Next, create instances of Menu
that will define the selections displayed on the bar. Following are the constructors for
Menu:
Menu( )
Menu(String optionName)
Here, optionName specifies the name of the menu [Link] menu items are of
type
MenuItem. It defines these constructors:
MenuItem( )

MenuItem(String itemName)
Here, itemName is the name shown in the menu.
//Menu Demo
import
[Link].*;
import [Link].*;
class MenuFrame extends Frame implements ActionListener
{
MenuBar mbr;Menu file, edit;
MenuItem m1, m2, m3,m4, m5, m6;
MenuFrame()
{setSize(300,300); setVisible(true); setTitle("Menu Frame"); mbr=new MenuBar();
setMenuBar(mbr);
file=new Menu("File");
edit=new Menu("Edit");
m1=new MenuItem("New");
m2=new MenuItem("Save");
m3=new MenuItem("Close");
m4=new MenuItem("Copy");
m5=new MenuItem("Paste");
m6=new MenuItem("Select All");
[Link](m1);[Link](m2);[Link](m3);[Link](m4);[Link](m5);[Link](m6);[Link](fil
e);[Link](edit);
CloseWin2 w=new CloseWin2(this);
addWindowListener(w);
[Link](w);
[Link](this);
}public void actionPerformed(ActionEvent ae)
{
ExDialog ed=new ExDialog(this);
[Link](200,200);
[Link](true);
}}
class ExDialog extends Dialog implements ActionListener
{
Button b;
ExDialog(MenuFrame
mm)
{super(mm,"Demo Dialog",false);

setLayout(new FlowLayout());
add(b=new Button("cancel"));
[Link](this);
}public void actionPerformed(ActionEvent ae)
{
[Link]();
}}
class CloseWin2 extends WindowAdapter implements ActionListener
{
MenuFrame f;
CloseWin2(MenuFrame mf)
{
f=mf;
}public void windowClosing(WindowEvent we)
{[Link](false);
}public void actionPerformed(ActionEvent ae)
{[Link](false);
}}

class DemoMenu
{public static void main(String args[])
{MenuFrame m=new MenuFrame();
}}Output:
MODULE -4 CHAPTER NO– 07

Event Handling
Lecture-36

Learning Objectives:
The students will be able to un
7.1 Event Handling

Event Handling
Event handling is fundamental to Java programming because it is used to create event driven
programs eg
• Applets
• GUI based windows application
• Web Application

• Event handling is at the core of successful applet programming. Most events


to which the applet will respond are generated by the user. The most commonly
handled events are those generated by the mouse, the keyboard, and various
controls, such as a push button.

• Events are supported by the [Link] package.


The Delegation Event Model
• The modern approach to handling events is based on the delegation event
model, whichdefines standard and consistent mechanisms to generate and process
events.
• Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.

• The advantage of this design is that the application logic that processes
events is cleanly separated from the user interface logic that generates those
events. A user interface element is able to "delegate" the processing of an event to
a separate piece of code.

• In the delegation event model, listeners must register with a source in order
to receive an event notification. This provides an important benefit: notifications
are sent only to listeners that want to receive them.

EVENTS
• In the delegation model, an event is an object that describes a state change in
a source. It can be generated as a consequence of a person interacting with the
elements in a graphical user interface. Some of the activities that cause events to

be generated are pressing a button, entering a character via the keyboard, selecting
an item in a list, and clicking the mouse.

• Events may also occur that are not directly caused by interactions with a user
interface.
• For example, an event may be generated when a timer expires, a counter
exceeds a value, software or hardware failure occurs, or an operation is completed.
EVENT SOURCES
• A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one
type of event. A source must register listeners in order for the listeners to receive
notifications about a specific type of event. Each type of event has its own
registration method.

• Here is the general form:


• public void add Type Listener( Type Listener el )

EVENT LISTENERS
• A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to
receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications. The methods that receive and
process events are defined in a set of interfaces found in [Link].

• For example, the MouseMotionListener interface defines two methods to


receive notifications when the mouse is dragged or moved.

EVENT CLASSES
• The classes that represent events are at the core of Java's event handling
mechanism. At the root of the Java event class hierarchy is EventObject, which is
in [Link]. It is the superclass for all events.

• It’s one constructor is shown here:


• EventObject(Object src )

• EventObject contains two methods: getSource( ) and toString( ) .

• The getSource( ) method returns the source of the event. Ex: Object getSource( )
• toString( ) returns the string equivalent of the event.
• The package [Link] defines several types of events that are
generated by various user interface elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following
integerconstants that can be used to identify them:
MOUSE_CLICKED The user clicked the
mouse. MOUSE_DRAGGED The user dragged the
mouse. MOUSE_ENTERED The mouse entered a
component. MOUSE_EXITED The mouse exited
from a component. MOUSE_MOVED The mouse
moved.
MOUSE_PRESSED The mouse was pressed. MOUSE_RELEASED The mouse
was released. MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).
EVENT LISTENER INTERFACES
When an event occurs, the event source invokes the appropriate method defined by the
listenerand provides an event object as its argument
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released,
or typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
The delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the
[Link] package.

The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an
action event [Link] general form is shown here: void
actionPerformed(ActionEvent ae )
MODULE -4 CHAPTER NO– 07

Event Handling
Lecture-37

Learning Objectives:
The students will be able to understand
7.2 Handling Mouse Events

The MouseListener Interface


This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is
called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( )
methods are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:


void mouseClicked(MouseEvent me )
void mouseEntered(MouseEvent me )
void mouseExited(MouseEvent me )
void mousePressed(MouseEvent me )
void mouseReleased(MouseEvent me )
The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.
Their general forms are shown here:
void mouseDragged(MouseEvent me ) void mouseMoved(MouseEvent me )

The TextListener Interface


This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field.

Its general form is shown here: void textChanged(TextEvent te )


Handling Mouse Events
To handle mouse events, we must implement the MouseListener and the MouseMotion Listener
interfaces.

EX: // Demonstrate the mouse event handlers.

import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{ String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
mouseX = 0; // save coordinates
mouseY = 10;
msg = "Mouse clicked.";repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save
coordinates mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save
coordinate s mouseX= 0;
mouseY = 10;
msg = "Mouse exited.";repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me) {
// save coordinates mouseX = [Link](); mouseY = [Link](); msg = "Down"; repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {
1. save
coordinates mouseX = [Link](); mouseY = [Link](); msg= "Up";repaint();}

Handle mouse dragged.


public void mouseDragged(MouseEvent me)
{
save coordinatesmouseX = [Link]();

mouseY = [Link]();msg
= "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}
// Display msg in applet window at current X,Y location. public
void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
}
}
MODULE -4 CHAPTER NO– 07

Event Handling
Lecture-38

Learning Objectives:
The students will be able to understand

7.3 Handling Keyboard Events

Objective: To echo keystrokes to the applet window and shows the pressed/released
status of each key in the status window

Which listener interface needs to be implemented byApplet?

KeyListener Interface

What are the methods defined by KeyListener Interface?

keyPressed(KeyEvent e)
keyReleased(KeyEven e)

keyTyped(KeyEvent e)

When a key is pressed, a KEY_PRESSED event is generated. This results in a call


to the keyPressed( ) event handler. When the key is released, a KEY_RELEASED
event is generated and the keyReleased( ) handler is executed. If a character is
generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked.

Thus, each time the user presses a key, at least two and often three events are
generated. If all you care about are actual characters, then you can ignore the
information passed by the key press and release events.
EX: // Demonstrate the key
event handlers.

import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="SimpleKey"width=300 height=100> </applet>*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; //
output coordinatespublic
void init() {
addKeyListener(this);
requestFocus(); // request input focus
}

public void keyPressed(KeyEvent ke)


{ showStatus("Key Down"); }

public void
keyReleased(KeyEvent ke)
{showStatus("Key Up");
}

public void keyTyped(KeyEvent ke) { msg += [Link]();


repaint();
}

// Display keystrokes.
public void paint(Graphics g)
{ [Link](msg, X, Y); }

}
MODULE -4 CHAPTER NO– 07

Event Handling
Lecture-39

Learning Objectives:
The students will be able to understand
7.4 Adapter Classes
Java provides a special feature, called an adapter class , that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface.

Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ) . The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged( ) . The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListene
WindowAdapter WindowListener
EX: // Demonstrate an [Link] [Link].*;
import [Link].*;import [Link].*;
/*
<applet code="AdapterDemo" width=300 height=100></applet>*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));addMouseMotionListener(new
MyMouseMotionAdapter(this)); }
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
[Link]("Mouse clicked");
}
}

class MyMouseMotionAdapter extendsMouseMotionAdapter


{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
[Link]("Mouse dragged");
}
}
MODULE -4 CHAPTER NO– 07
Event Handling
Lecture-40

Learning Objectives:
The students will be able to understand
7.5 Inner Classes
Not having to implement all of the methods defined by the MouseMotionListener
and MouseListener interfaces saves a considerable amount of effort.

An inner class is a class defined within anotherclass, or even within an


expression.
Let us see how inner classes can be used to simplify the code when using
event adapterclasses.

7.5.1 Use of Inner Class

Here, InnerClassDemo is a top-level class that extendsApplet.


MyMouseAdapter is an inner class that extends
MouseAdapter.
Because MyMouseAdapter is defined within the scope of InnerClassDemo, it
has access to all of the variables and methods within the scope of that class.
Therefore, the mousePressed( ) method can call the showStatus( ) method
directly.
It no longer needs to do this via a stored reference to the applet. Thus, it
is no longer necessary to pass MyMouseAdapter( ) a reference to the
invoking object.
// Source Code
import [Link].*;import [Link].*;
/*<applet code="InnerClassDemo" width=200 height=100></applet> */
public class InnerClassDemo extends Applet {public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter { public void
mousePressed(MouseEvent me) { showStatus("Mouse Pressed");
}
}
}
7.5.2 Anonymous Inner Class

A class that has no name is known as anonymous inner class in java. It should be used if
you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:

[Link] Class (may be abstract or concrete).

[Link] Interface

[Link] anonymous inner class example using class

abstract class Person{

abstract void eat();}


class TestAnonymousInner{

public static void main(String args[]){Person p=new Person(){


void eat(){[Link]("nice fruits");}

};

[Link]();

}}
Internal Working:

1.A class is created but its name is decided by the compiler which extends the Person class
and provides the implementation of the eat() method.
[Link] object of Anonymous class is created that is referred by p reference variable of
Person type.

[Link] inner class: using interface


interface Eatable{void eat();
}
class TestAnnonymousInnerClass{ public static void main(String
args[]){Eatable e=new Eatable(){
public void eat(){[Link]("nice fruits");}
};
[Link]();}}
Internal Working
A class is created but its name is decided by the compiler which implements the
Eatable interface and provides the implementation of the eat() method.
An object of Anonymous class is created that is referred by p reference variable of Eatable
[Link] Inner Classes
Let us see how an anonymous inner class can facilitate the writing of event
handlers.
// Anonymous inner class demo.
import [Link].*;
import [Link].*;
Import [Link].*;
/* <applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>*/

public class AnonymousInnerClassDemo extendsApplet {

public void init() {

addMouseListener (new MouseAdapter() { public void mousePressed(MouseEvent


me) {showStatus("Mouse Pressed");
}

}); // header closed


}

The classAnonymousInnerClassDemo extendsApplet class.


 The init( ) method calls the addMouseListener( )method.
 Its argument is an expression that defines and instantiates an
anonymous inner class.
 Analyze this expression carefully. The syntax new MouseAdapter(){...}
indicates to the compiler that the code between the braces defines an anonymous inner
class..

 Furthermore, that class extends MouseAdapter. This new class is not named, but it is
automatically instantiated when this expression is executed.
 Because this anonymous inner class is defined within the scope of Anonymous Inner
Class Demo, it has access to all of the variables and methods within the scope of that
class. Therefore, it can call the showStatus( ) method directly.
 Inner and Anonymous inner classes simplify event Handling

 A source generates an event and sends it toone or more listeners.

 The listener simply waits until it receives anevent.

 Once an event is received, the listener processes the event and


then returns.

 The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logicthat generates those events.

 In the delegation event model, listeners must register with a source in order to
receive an event notification.

Benefit: notifications are sent only to listenersthat want to receive them.

 In original Java 1.0 approach, an event waspropagated up the containment hierarchy


until it was handled by a component.

 This required components to receive events that they did not process, and it
wasted valuable time.
Assignment : 4

Short Type Questions

1. Define AWT
Ans : The Full Form Of AWT is Abstract Window Toolkit. The Abstract Window Toolkit is a
platform-dependent API used to develop GUI (Graphical User Interface) or window-based applications
in Java. Basically, the AWT is a member of the Java Foundation Classes – the approved API
implementing a GUI for a Java program.

2. List at least 5 AWT controls.


Ans : Java provides [Link] package that supports various AWT controls like Label, Button,
CheckBox, CheckBox Group, List, Text Field etc.
3. Define Textfield. How is it created?
Ans : TextField object is a text component that allows for the editing of a single line of text. For
example, the following image depicts a frame with four text fields of varying widths. Two of these text
fields display the predefined text "Hello" .
TextField object is a text component that allows for the editing of a single line of text. For example,
the following image depicts a frame with four text fields of varying widths. Two of these text fields
display the predefined text "Hello" .
4. Define Layout Manager.
Ans :Layout managers are software components used in widget toolkits which have the ability to lay
out graphical control elements by their relative positions without using distance units.
5. Differentiate between checkbox and radio button.
Ans :Checkboxes and radio buttons are elements for making selections. Checkboxes allow the user to
choose items from a fixed number of alternatives, while radio buttons allow the user to choose exactly
one item from a list of several predefined alternatives.
6. Distinguish between choice and list box.
Ans : Listboxes and dropdowns are compact UI controls that allow users to select options. Listboxes
expose options right away and support multi-selection while dropdowns require a click to see options
and support only single-selection
7. Which method of TextField class is used to create a password field?
Ans :The JPasswordField class, a subclass of JTextField , provides specialized text fields for
password entry.
8. What are source and listener?
Ans: Source: A source is an object that generates an event. This occurs when the internal state of that
object changes in some way.
Listener: A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about specific
types of events.

9. What is adapter class?


Ans: An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface. You can define a new class to act listener by extending
one of the adapter classes and implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( )and mouseMoved( ).

10. What is an event and what are the models available for event handling?
Ans: An event is an event object that describes a state of change in a source. In other words, an event
occurs when an action is generated, like pressing a button, clicking the mouse, selecting a fist, etc.

There are two types of models for handling events and they are:

a) event-inheritance model and


b) event-delegation model

[Link] is an event and what are the models available for event handling?
Ans: An event is an event object that describes a state of change in a source. In other words, an event
occurs when an action is generated, like pressing a button, clicking the mouse, selecting a fist, etc.
There are two types of models for handling events and they are:

a) event-inheritance model and


b) event-delegation model

[Link] are the advantages of the model over the event-inheritance model?
Ans: The event-delegation model has two advantages over the event-inheritance model. They are:

a) It enables event handling by objects other than the ones that generate the events. This allows a clean
separation between a component’s design and its use.

b) It performs much better in applications where many events are generated. This performance
improvement is due to the fact that the event-delegation model does not have to repeatedly process
unhandled events as is the case of the event inheritance.

13. What is the highest-level event class of the event-delegation model?


Ans: The java. [Link] class is the highest-level class in the event- delegation class hierarchy.
14. What event results from the clicking of a button?
Ans: The ActionEvent event is generated as the result of the clicking of a button.

15. How can a GUI component handle its own events?


Ans: A component can handle its own events by implementing the required event-listener interface and
adding itself as its own event listener.

16. What is the purpose of the enableEvents( ) method?


Ans : The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is
enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used
by objects that handle events by overriding their event-dispatch methods.

17. What interface is extended by AW^T event listeners?


Ans : All AWT event listeners extend the java. [Link] interface.

18. How can a GUI component handle its own events?


Ans: A component can handle its own events by implementing the required event-listener interface and
adding itself as its own event listener.

19. What is the purpose of the enableEvents( ) method?


Ans: The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is
enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used
by objects that handle events by overriding their event-dispatch methods.

20. What is an ActionEvent?

Ans : An action event is a semantic event which indicates that a component-defined action occurred.

- The ActionListener interface gets this ActionEvent when the event occurs.

- Event like Button pressed is an action event.

- It is defined in '[Link]' package.

21. What is the difference between the paint() and repaint() methods?

Ans :
paint() repaint()
The paint() method is called when some action Whenever a repaint method is called, the update method is
is performed on the window. also called along with paint() method.
This method supports painting via graphics This method is used to cause paint() to be invoked by the
object. AWT painting thread.
Long Type Questions

1. Discuss RMI (Remote Method Invocation) with neat diagram.

2. What are layout managers? Discuss different layout managers available in java.

3. Define check box. Discuss with an example how to handle events in a checkbox.

4. Write a java program to design a data enter from to enter name, branch, address of the students using

text fields, buttons and scroll bar respectively.


5. Differentiate between AWT and Swing based GUI.

6. List any four methods of the MouseListener interface.

7. What is the use of layout manager?


8. Write a program to create a screen which contains which contains three checkboxex(DOS, Linux,
and Windows) and displays the selected items in a textbox.
9. A class requires to handle events on a menu and checkbox. Which listener shoulimplement?
10. What is Enent handler ? Write differentiate between Mouse enevt handling & keyboard event handling ?

You might also like