Java AWT Controls and Components Guide
Java AWT Controls and Components Guide
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.
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
Learning Objectives:
The students will be able to understand
6.2 User Interface Components
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)
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].*;
3. First(){
10. }
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(){
6. 6. [Link](30,50,80,30);
7. [Link](b);
8. [Link](300,300);
9. [Link](null);
10. [Link](true);
11. }
14. 14. }}
Examples of GUI based Applications
Mobile Applications
Navigation Systems
import [Link].*;
import [Link].*;
</applet>*/
setBackground([Link]);
SetForeground([Link]);
add(l1);
add(l2);
}
Public paint(graphics g)
[Link](“LabelDemo”,100,100);
import [Link].*;
import [Link].*;
</applet>*/
add(b1);
add(b2);
add(b3);
[Link](this);
[Link](this);
[Link](this);
Public paint(graphics g)
[Link](“ButtonDemo”,100,100);
}
String str=[Link]();
if([Link](“Red”))
setBackground([Link]);
else if([Link](“Blue”))
setBackground([Link]);
else
setBackground([Link]);
import [Link].*;
import [Link].*;
import [Link].*;
Checkbox
</applet>*/
setBackground([Link]);
SetForeground([Link]);
add(c1);
add(c2);
add(c3);
add(c4);
Public paint(graphics g)
[Link](“CheckBoxDemo”,100,100);
CheckboxGroup
</applet>*/
setBackground([Link]);
SetForeground([Link]);
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:
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.
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.
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
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.
Learning Objectives:
The students will be able to understand
6.3 AWT 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:
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>*/
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].*;
String s="";
Output:
{
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)
{
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
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
• 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.
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].
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.
• 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.
Event Handling
Lecture-37
Learning Objectives:
The students will be able to understand
7.2 Handling Mouse Events
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);
}
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
Objective: To echo keystrokes to the applet window and shows the pressed/released
status of each key in the status window
KeyListener Interface
keyPressed(KeyEvent e)
keyReleased(KeyEven e)
keyTyped(KeyEvent e)
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
keyReleased(KeyEvent ke)
{showStatus("Key Up");
}
// 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.
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.
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] Interface
};
[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.
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
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.
This required components to receive events that they did not process, and it
wasted valuable time.
Assignment : 4
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.
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:
[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:
[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.
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.
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
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