SlideShare a Scribd company logo
1
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
UNIT-III: AWT & Event Handling
* Introduction to AWT *
 AWT stands for Abstract Window Toolkit. It is provided in java as a java
package i.e. ‘java.awt”
 The ‘java.awt’ contains numerous classes and methods that allow us to create
and manage window applications.
 This AWT package allows a programmer to Create a standard window, dialog
box, controls, etc.
 In windows, controls are nothing but window element that allow user to
interact with your application. For example, Command Button, Scroll Bar,
Menu Bar, etc.
 The following figure shows the AWT class hierarchy:
 Component:
o Component is an abstract class; it contains attributes of visual components.
o All user interface elements like button, label, checkbox, scrollbar etc. are
displayed on the screen are subclasses of class Component.
Object
Container
Panel
Applet
Wndow
Frame
Dialog
Label Button Checkbox Scrollbar TextComponent
TextField TextArea
Component
2
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 Container:
o Container is a class that defined positioning of controls i.e. layout within
the window that we perform in .Net just by drag and drop.
 Panel:
o This class is used to create panel window, the window not having border,
title bar, and menu bar. Ex. Applet window
 Frame:
o This class is used to create a standard window i.e. having border, title bar
and menu bar.
 The ‘java.awt’ is one of the java’s largest package.
 The following table shows few of the classes defined in ‘java.awt’ package.
# Class name Description
1 Frame
Creates a standard window that has t title bar, resize
corners, and a menu bar.
2 Label Creates a label that displays a string.
3 Button Creates a push button control.
4 Checkbox Creates a checkbox control.
5 TextField Creates a single-line edit control.
6 TextArea Creates a multiline edit control.
7 List Creates a list from which the user can choose..
8 Scrollbar Creates a scroll bar control.
9 BorderLayout
The border layout manager. Border supports five
positions on window at which we can place control:
North, South, East West, and Center.
10 CardLayout
The card layout manager. Card layouts emulate
index cards. Only the one on top is showing.
11 FlowLayout
The flow layout manager. Flow layout positions
components left to right, top to bottom.
12 GridLayout
The grid layout manager. Grid layout displays
components in a two-dimensional grid.
3
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Working with Frame Window *
 A frame is thought of as a “window”.
 To create a frame window, we have to follow TWO steps:
1. By extending ‘Frame’ class.
2. By creating object of ‘Frame’ class.
1. Creating frame window by extending ‘Frame’ class:
2. Creating frame window By creating object of ‘Frame’ class:
import java.awt.*;
class MYWINDOW extends Frame
{
MYWINDOW()
{
setSize(500,400);
setTitle(“My First frame window”)
setVisible(true);
setLayout(null); // No layout manager(Default: Border Layout
}
public static void main(String args[])
{
MYWINDOW obj= new MYWINDOW();
}
}
import java.awt.*;
class MYWINDOW
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(500,400);
obj.setTitle(“My First frame window”)
obj.setVisible(true);
obj.setLayout(null); // No layout manager(Default: Border Layout
}
}
4
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 The output of the above both programs is same as shown below:
* Label Control *
 A label is window element that contains a string, which it displays.
 The class ‘Label’ defines the following THREE constructors used to create
label control:
1. Label() : This constructor creates a blank label.
2. Label(String str): This constructor creates a label that contains a string
‘str’. This string is Left-justified.
3. Label(String str, int how) :This constructor creates a label that contains
a string ‘str’ using alignment ‘how’. The value of ‘how’ must be
one of these constants: Label.LEFT, Label.RIGHT or Label.CENTER.
5
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 For example,
 The output of the above program is as follows:
import java.awt.*;
class LABEL
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(null);
obj.setTitle("Program on Label control");
Label x=new Label("Enter First Name:");
x.setBounds(40,40,200,30);
Label y=new Label("Enter Last Name:", Label.RIGHT);
y.setBounds(40,80,200,20);
obj.add(x);
obj.add(y);
}
}
6
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Button Control *
 A command button is a component that has a label printed over it and
generates an event when it is pressed.
 The class ‘Button’ defines the following TWO constructors used to create
button control:
Constructor
Prototype
Purpose
Button (); It creates a blank button.
Button (String str);
It creates a button that contains a string ‘str’ as
button label.
For example,
import java.awt.*;
class BUTTON
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(null);
obj.setTitle("Program on Button control");
Button B1=new Button();
B1.setBounds(40,40,100,20);
B1.setLabel("OK");
Button B2=new Button("CANCEL");
B2.setBounds(40,70,100,20);
obj.add(B1);
obj.add(B2);
}
}
7
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 The output of above program is as follows:
* Checkbox Control *
 A check box is a component that allow user to select the option. By default
they are in square box shape.
 A check box control has ‘label’ and ‘state’ these two attributes.
 The state of check box is either ‘checked’ or ‘unchecked’.
 The class ‘Checkbox’ is defined in ‘java.awt’ package with following
THREE types of constructors to create check boxes.
Constructor Purpose
Checkbox() It creates a check box with blank label.
Checkbox(String str) It creates a check box whose label is specified by string ‘str’.
Checkbox(String str,
boolean X)
It creates a check box with label ‘str’ and also allow to set
initial state i.e. true or false.
8
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
For example,
The output of above program is:
NOTE: Here we used layout manager ‘FlowLayout’. So no need to set bounds
for control that we are positioning within window.
import java.awt.*;
class CHECKBOX
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on Checkbox control");
Checkbox c1,c2,c3;
c1=new Checkbox();
c2=new Checkbox("Marks Memo");
c3=new Checkbox("TC",true);
obj.add(c2); obj.add(c3); obj.add(c1);
}
}
9
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Text field Control *
 A text field is a single line component that allow user to enter strings and to
edit the string present in it.
 The class ‘TextField’ defines the following FOUR constructors used to create
text field control:
Constructor Purpose
TextField() It creates a blank field of default width of 2 characters.
TextField(int n) It creates a text field which is ‘n’ characters wide.
TextField(String str) It creates a text field and initializes a string ‘str’ to it.
TextField(String str,
int n)
It creates a text field and initializes a string ‘str’ to it and sets
its width to ‘n’ characters.
For example,
import java.awt.*;
class TEXTFIELD
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on text field control");
TextField text1,text2;
text1=new TextField();
text1.setText("Hello India");
text1.setEditable(false);
text2=new TextField("Hello World");
obj.add(text1);
obj.add(text2);
}
}
10
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
The output of above program is:
* Text area Control *
 A text area is a component that allow user to enter multiple line of text and to
edit.
 The class ‘TextArea’ defines the following FIVE constructors used to create
text area control:
Constructor Purpose
TextArea() It creates a default text area control.
TextArea(int x, int y) It creates a text area control of ‘x’ number of lines and of
width ‘y’ characters.
TextArea(String str) It creates a text area and initializes string ‘str’ to it.
TextArea(String str, int x,
int y)
It creates a text area of ‘x’ lines, of width ‘y’ character
and initializes string ‘str’ to it.
TextArea(String str, int x,
int y, int sBars)
It creates a text area of ‘x’ lines, of width ‘y’ character
and initializes string ‘str’to it having scroll bars specified
by ‘sBars’.
11
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
For example,
The output of above program is:
import java.awt.*;
class TEXTAREA
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on text area control");
TextArea TA1,TA2,TA3;
TA1=new TextArea();
TA2=new TextArea("Hello Indian Hello
World",10,4,TextArea.SCROLLBARS_BOTH);
TA3=new TextArea(5,10);
obj.add(TA1);
obj.add(TA2);
obj.add(TA3);
}
}
12
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* List Control *
 The class ‘List’ provides following THREE constructors to create list control.
 By default multi-selection property of list control is FALSE.
Constructor Purpose
List() It creates a list control that allows only one item to be selected
at a time with default FOUR rows.
List( int numRows) It create a list control and integer ‘numRows’ is number of
items in the list that will always be visible.
List(int numRows,
boolean flag)
It creates a list control in which multiple selections are allowed
or not is specified by ‘flag’ i.e. boolean value ‘true’ or ‘false’.
For example,
import java.awt.*;
class LIST
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on list control");
List x=new List(); //List X
x.add("Udgir");
x.add("Latur");
List y=new List(1); // List Y
y.add("Amravati");
y.add("Latur");
y.add("Banglore");
List z=new List(5,true); // List Z
z.add("Udgir");
z.add("Amravati");
z.add("Banglore");
obj.add(x); obj.add(y); obj.add(z);
}
}
13
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
The output of above program is:
* Scrollbar Control *
 A scrollbar control is used to view the contents of the page which can’t be
displayed on screen in one page.
 Two types of scrollbars are available i.e. Horizontal and Vertical.
 Each scroll bar is assigned with a range of values i.e. ‘Minvalue’ and
‘Maxvalue’(Integers).
 A scrollbar consists of several individual parts: Arrows on each end and a
slider box(Thumb).
 The position of slider box on the scrollbar indicates the current value of the
scrollbar.
 The class ‘Scrollbar’ provides following THREE constructors to create
scrollbar.
14
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
Constructor Purpose
Scrollbar() It creates a default vertical scrollbar.
Scrollbar(int style) It creates either vertical OR horizontal scrollbar. The
‘style’ can take one of the TWO values
Scrollbar.VERTICAL(0) or Scrollbar.HORIZONTAL(1)
Scrollbar(int style,
int initial,
int thumbSize,
int min,
int max)
It creates scrollbar with specified initial value. It also
allow to specify Minvalue and Maxvalue. The
‘thumbSize’ determines the width of the slider box.
For example,
import java.awt.*;
class SCROLLBAR
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on scrollbar control");
Scrollbar x=new Scrollbar();
Scrollbar y=new Scrollbar(Scrollbar.HORIZONTAL);
Scrollbar z=new Scrollbar(Scrollbar.HORIZONTAL,500,500,0,1000);
z.setPreferredSize(new Dimension(200,200)); //Dimension(width,height)
y.setPreferredSize(new Dimension(100,200)); //Dimension(width,height)
obj.add(x);
obj.add(y);
obj.add(z);
}
}
15
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
The output of above program is:
* Layout Manager *
 Layout means the arrangement of components within the container.
 In java, container is nothing but a window.
 Positioning controls within the window is handled in java by some classes
defined, called Layout Managers.
 In java, the following FIVE classes represents different layout managers:
1. java.awt.BorderLayout
2. java.awt.GridLayout
3. java.awt.FlowLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
16
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* BorderLayout Manager *
 This layout is used to arrange the components in FIVE regions: north, south,
east, west and center. Each region(area) may contain only one component.
 It is default layout for frame(standard) window.
 The BorderLayout class contains following five defined constant’s:
o public static final int NORTH
o public static final int SOUTH
o public static final int EAST
o public static final int WEST
o public static final int CENTER (Default)
 For example,
The output of above program is as follows:
import java.awt.*;
class BORDERLAYOUT
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
obj.setTitle("Program on list control");
BorderLayout mgr=new BorderLayout();
obj.setLayout(mgr);
Button b1=new Button("Hello");
Button b2=new Button("World");
Button b3=new Button("Thank you!");
obj.add(b1,BorderLayout.WEST);
obj.add(b2,BorderLayout.NORTH);
obj.add(b3); // Default CENTER
}
}
17
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
18
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* GridLayout Manager *
 The grid layout divides the window into rows and columns.
 Each cell is referred as a single Grid.
 One component is displayed in one grid of the window.
 For example,
The output of above program is as follows:
import java.awt.*;
class GRIDLAYOUT
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setTitle("Program on Grid layout manager");
GridLayout mgr=new GridLayout(2,2);
obj.setLayout(mgr);
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
obj.add(b1); obj.add(b2);
obj.add(b3); obj.add(b4);
}
}
19
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* FlowLayout Manager *
 The flow layout is used to arrange the components in a line one after another(in
a flow).
 It is default layout manager for panel(applet) window.
 This layout manager support THREE alignments by defining following
integer constants in ‘FlowLayout’ class:
 public static fine int LEFT
 public static fine int RIGHT
 public static fine int CENTER(Default)
 For example,
The output of above program is as follows:
import java.awt.*;
class FLOWLAYOUT
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setTitle("Program on flow layout manager");
FlowLayout mgr=new FlowLayout(FlowLayout.RIGHT);
obj.setLayout(mgr);
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
obj.add(b1);
obj.add(b2);
obj.add(b3);
obj.add(b4);
}
}
20
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
21
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* CardLayout Manager *
 This layout manager is different among all other layout managers.
 This layout manager defines a container and allow to add any number of
panel windows containing group of components, but only one panel
window can be shown at a given time.
 The panel window is referred as a card.
 Only one card is shown at a time and other present but hidden below it.
 For example,
import java.awt.*;
class CARDLAYOUT
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setTitle("Program on card layout manager");
CardLayout mgr=new CardLayout();
obj.setLayout(mgr);
Panel cricket=new Panel(); //Creating card for CRICKET
cricket.add(new Checkbox("Jaques Kallis"));
cricket.add(new Checkbox("Virat Kohli"));
Panel tennis=new Panel(); // Creating card for TENNIS
tennis.add(new Checkbox("Pit Sampras"));
tennis.add(new Checkbox("John Edberg"));
obj.add(cricket,"X"); // Adding group(card) to container
obj.add("Y",tennis); // Addign group(card) to container
mgr.show(obj,"Y");
}
}
22
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
The output of above program is as follows:
* CardLayout Manager *
 This layout manager is different among all other layout managers.
 This layout manager defines a container and allow to add any number of
panel windows containing group of components, but only one panel
window can be shown at a given time.
 The panel window is referred as a card.
 Only one card is shown at a time and other present but hidden below it.
23
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 For example,
The output of above program is as follows:
import java.awt.*;
class CARDLAYOUT
{
public static void main(String args[])
{
Frame obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setTitle("Program on card layout manager");
CardLayout mgr=new CardLayout();
obj.setLayout(mgr);
Panel cricket=new Panel(); //Creating card for CRICKET
cricket.add(new Checkbox("Jaques Kallis"));
cricket.add(new Checkbox("Virat Kohli"));
Panel tennis=new Panel(); // Creating card for TENNIS
tennis.add(new Checkbox("Pit Sampras"));
tennis.add(new Checkbox("John Edberg"));
obj.add(cricket,"X"); // Adding group(card) to container
obj.add("Y",tennis); // Addign group(card) to container
mgr.show(obj,"Y");
}
}
24
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Event Delegation Model *
 Event Delegation model is mechanism used to perform event handling in Java.
 The principles of event delegation model are:
1. A source(component) generates an event and sends it to one or more
listeners.
2. The listeners simply waits until it receives an event. Once received, the
listener processes the event and then returns.
NOTE : Listeners must be registered with a source.
1. Event :
 An event is an object of event class that describes a state change in a source.
 For example, Event may be generated when button is pressed, item in a list
is selected or mouse is clicked.
2. Source :
 A source is an object of control (e.g. Label, Button, etc.) that generates an
event.
 A single source may generate more than one type of events.
 A source must be registered with listeners. The general form of registration
is:
25
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
Here, ‘add’ and ‘Listener’ are keywords. A ‘Type’ is name of the event. The ‘el’
is reference to event listener.
For example,
Button b1=new Button();
b1.addActionListener(this);
When button ‘b1’ is pressed, notification to listener will be sent.
3. Listener :
 A listener is an object that is notified when an event occurs. It has TWO major
requirements:
1. It must have been registered with one or more sources to receive
notifications about specific event types.
2. It must be implemented to receive and process these notifications.
 The methods that can receive and process the events are defined in built-in
interfaces.
 A single interface has one or more methods declared in it.
 For example, ActionListener interface has only one method i.e.
ActionPerformed() method but MouseListener interface has multiple
methods for different event that mouse can generate.
public void addTypeListener(TypeListener el);
26
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Java AWT Events *
 Here we will discuss various events that we can handle by using event
delegation model in java.
 The following table shows various events and corresponding classes defined
in ‘java.awt.event’ package whose object is automatically generated when
event occurs.
Event
Event Class whose object is
generated
Window activated
WindowEvent
Window closed
Window is being closed
Window is deactivated
Window is de-iconified
Window is iconified
Window is opened
Button pressed ActionEvent
Adjustment using scrollbar AdjustmentEvent
Control gets focus
FocusEvent
Control loses focus
State of control changed(checkbox) ItemEvent
Change occurs in text field or text area TextEvent
Mouse button is pressed and released at a time
MouseEvent
Mouse pointer enters into control
Mouse pointer leaves control
Mouse Button is pressed
Mouse Button is released
Mouse dragged
MouseMotionEvent
Mouse moved
27
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Sources of Event *
 Source of the event is the component/control (like, button, checkbox, etc) on
which event is occurring.
 Particularly, in a java program an object of component/control is a source of
an event.
 The following table shows the various event and possible sources of the event.
Event Sources of Event
Window activated
A panel or frame window
Window closed
Window is being closed
Window is deactivated
Window is de-iconified
Window is iconified
Window is opened
Button pressed A Button
Adjustment using scrollbar Scrollbar
Control gets focus
Any Control
Control loses focus
State of control changed(checkbox) Checkbox, radio button
Change occurs in text field or text area Text field or Text area
Mouse button is pressed and released at a time
Any Control
Mouse pointer enters into control
Mouse pointer leaves control
Mouse Button is pressed
Mouse Button is released
Mouse dragged
Input device mouse
Mouse moved
28
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Event Listener Interface *
In java number of interfaces defined that contain methods to handle the generated
events. Hence these interfaces are also called event handlers.
For each event class there is its corresponding listener interface is defined in
“java.awt.event” package.
The following table shows event class and associated listener interface names.
Event Class Listener Interface
WindowEvent WindowListener
MouseEvent MouseListener
MouseMotionEvent MouseMotionListener
FocusEvent FocusListener
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ItemEvent ItemListener
TextEvent TextListener
 A single listener interface defined with one or more abstract methods to handle
different events as described below:
Abstract methods declared in interface WindowListener
Method Purpose
windowActivated() invoked when a window is activated.
windowDeactivated() Invoked when window is deactivated
windowClosing() Invoked when window is being closed.
windowOpened() Invoked when window is get opened.
windowIconified() Invoked when window is iconified.
windowDeiconified() Invoked when window is de-iconified.
windowClosed() Invoked when widow is closed.
29
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
Abstract methods declared in interface MouseListener
Method Purpose
mouseCliked() Invoked when mouse is pressed and released at a same time
mousePressed() Invoked when mouse button is pressed.
mouseReleased() Invoked when mouse button is released.
mouseEntered() Invoked when mouse pointer enters into control.
moueseExited() Invoked when mouse pointer leaved control.
Abstract methods declared in interface MouseMotionListener
Method Purpose
mouseDragged() Invokes multiple times as the mouse is dragged.
mouseMoved() Invokes multiple times as the mouse is moved.
Abstract methods declared in interface FocusListener
Method Purpose
focusGained() Invoked when control gets keyboard focus.
focusLost() Invoked when control loses keyboard focus.
Abstract methods declared in interface ActionListener
Method Purpose
actionPerformed() Invoked when button control is pressed.
Abstract methods declared in interface AdjustmentListener
Method Purpose
adjustmentValueChanged() Invoked when user scrolling using scrollbar button.
Abstract methods declared in interface ItemListener
Method Purpose
itemStateChanged() Invoked when state of the checkbox/radio button changed.
Abstract methods declared in interface TextListener
Method Purpose
itemStateChanged() Invoked when state of the checkbox/radio button changed.
30
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Adapter Classes *
 To handle event, we have to implement the interfaces defined as listeners.
 We know that when an interface is implemented all the abstracts methods of
that interface must be defined in a class which is implementing it.
 A listener interface may contain multiple abstract methods.
 We cannot implement an interface by defining few of the methods of the
interface rather we have to define all the abstract methods of that interface.
 Java provides special classes called Adapter classes, that we can use to handle
only some of the events by implementing only those methods that we require
to handle the events.
 For example, The interface FocusListener has two methods to handle two
events i.e. focusGained() and focusLost(). If we want to handle only one
event, then by using adapter class associated with FocusListener interface we
can implement only one of these two methods.
 The following table shows the adapter classes provided in Java and its
associated interface listener:
Adapter Class Listener Interface
WindowAdapter WindowListener
FocusAdapter FocusListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
31
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
For example,
 In above code, we are implementing FocusListner interface which has two
abstract methods i.e. focusGained() and focusLost().
 This code will produce error that implementation of focusLost() method is
missing. That means we must define both abstract methods while
implementing FocusListener interface. Although we don’t want handle focus
lost event.
 This problem will be resolved by using adapter class FocusAdapter as shown
in following program.
import java.awt.*; import java.awt.event.*;
public class test implements FocusListener
{
Frame obj;
public static void main(String args[])
{
test x=new test();
}
test()
{
obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
TextField t1=new TextField(); obj.add(t1);
Button b1=new Button("red"); obj.add(b1);
b1.addFocusListener(this);
}
// Only focusGained event we want handle
public void focusGained(FocusEvent z)
{
obj.setBackground(Color.RED);
}
}
32
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
 The error occurred in previous programs is removed in this code by using
FocusAdapter Class instead of FocusListener interface.
import java.awt.*; import java.awt.event.*;
public class test extends FocusAdapter
{
Frame obj;
public static void main(String args[])
{
test x=new test();
}
test()
{
obj=new Frame();
obj.setSize(400,300);
obj.setVisible(true);
obj.setLayout(new FlowLayout());
TextField t1=new TextField(); obj.add(t1);
Button b1=new Button("red"); obj.add(b1);
b1.addFocusListener(this);
}
// Only focusGained event we want handle
public void focusGained(FocusEvent z)
{
obj.setBackground(Color.RED);
}
}
33
B.Sc. III (VI Sem)
Advance Java Programming (Unit-III)
Prepared by,
Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
* Inner Class *
 Inner classes are a security mechanism in Java.
 We know a class cannot be associated with the access modifier private, but if
we have the class as a member of other class, then the inner class can be made
private.
 Creating an inner class is quite simple. You just need to write a class within a
class.
In the given example, we make the inner class private and access the class through
a method.
Output:
This is inner class
class Outer_Demo
{
int num;
private class Inner_Demo // inner class
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class innerclass
{
public static void main(String args[])
{
Outer_Demo outer = new Outer_Demo();
outer.display_Inner();
}
}

More Related Content

What's hot (20)

PPT
Xml parsers
Manav Prasad
 
PPT
Lecture 21 - Preprocessor and Header File
Md. Imran Hossain Showrov
 
PPT
Working with frames
myrajendra
 
PPTX
Weblogic 101 for dba
Osama Mustafa
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PDF
Friend function in c++
University of Madras
 
PPTX
Test scenarios for sending & receiving emails
Morpheous Algan
 
PPT
Constructor and Destructor PPT
Shubham Mondal
 
PPT
friend function(c++)
Ritika Sharma
 
PPT
Preprocessor in C
Prabhu Govind
 
PDF
Exception handling
Pranali Chaudhari
 
PPTX
VB.NET:An introduction to Namespaces in .NET framework
Richa Handa
 
PDF
The New JavaScript: ES6
Rob Eisenberg
 
PPTX
Spring boot anane maryem ben aziza syrine
Syrine Ben aziza
 
PPT
Decision making and looping
Hossain Md Shakhawat
 
PPT
C sharp
Satish Verma
 
PDF
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
PPTX
Exception handling in java
Lovely Professional University
 
Xml parsers
Manav Prasad
 
Lecture 21 - Preprocessor and Header File
Md. Imran Hossain Showrov
 
Working with frames
myrajendra
 
Weblogic 101 for dba
Osama Mustafa
 
Constructor in java
Pavith Gunasekara
 
Java Streams
M Vishnuvardhan Reddy
 
Friend function in c++
University of Madras
 
Test scenarios for sending & receiving emails
Morpheous Algan
 
Constructor and Destructor PPT
Shubham Mondal
 
friend function(c++)
Ritika Sharma
 
Preprocessor in C
Prabhu Govind
 
Exception handling
Pranali Chaudhari
 
VB.NET:An introduction to Namespaces in .NET framework
Richa Handa
 
The New JavaScript: ES6
Rob Eisenberg
 
Spring boot anane maryem ben aziza syrine
Syrine Ben aziza
 
Decision making and looping
Hossain Md Shakhawat
 
C sharp
Satish Verma
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Exception handling in java
Lovely Professional University
 

Similar to B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling (20)

PPT
introduction to JAVA awt programmin .ppt
bgvthm
 
PPT
fdtrdrtttxxxtrtrctctrttrdredrerrrrrrawt.ppt
havalneha2121
 
PPT
awdrdtfffyfyfyfyfyfyfyfyfyfyfyfyyfyt.ppt
SulbhaBhivsane
 
PPT
1.Abstract windowing toolkit.ppt of AJP sub
YugandharaNalavade
 
PPT
Unit 1- awt(Abstract Window Toolkit) .ppt
Deepgaichor1
 
PPT
Advance Java Programming (CM5I) 1.AWT
Payal Dungarwal
 
PPT
events,key,life cycle-abstract window tool kit,abstract class
Rohit Kumar
 
PPSX
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
PPT
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
PPTX
AWT stands for Abstract Window Toolkit. AWT is collection of classes and int...
Prashant416351
 
PPTX
17625-1.pptx
BhaskarDharmadhikari
 
PPTX
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
PPTX
UNIT-I.pptx awt advance java abstract windowing toolkit and swing
utkarshabhope
 
PPTX
Lecture 2 Introduction to AWT (1).ppt.hello
mayurDharmik1
 
PPT
Java AWT Controls and methods, Listener classes
muthulakshmi279332
 
PDF
Session 9_AWT in java with all demonstrations.pdf
tabbu23
 
PPTX
AWT New-3.pptx
SarthakSrivastava70
 
PPTX
Swing component point are mentioned in PPT which helpgul for creating Java GU...
sonalipatil225940
 
introduction to JAVA awt programmin .ppt
bgvthm
 
fdtrdrtttxxxtrtrctctrttrdredrerrrrrrawt.ppt
havalneha2121
 
awdrdtfffyfyfyfyfyfyfyfyfyfyfyfyyfyt.ppt
SulbhaBhivsane
 
1.Abstract windowing toolkit.ppt of AJP sub
YugandharaNalavade
 
Unit 1- awt(Abstract Window Toolkit) .ppt
Deepgaichor1
 
Advance Java Programming (CM5I) 1.AWT
Payal Dungarwal
 
events,key,life cycle-abstract window tool kit,abstract class
Rohit Kumar
 
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
Basic of Abstract Window Toolkit(AWT) in Java
suraj pandey
 
AWT stands for Abstract Window Toolkit. AWT is collection of classes and int...
Prashant416351
 
17625-1.pptx
BhaskarDharmadhikari
 
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
UNIT-I.pptx awt advance java abstract windowing toolkit and swing
utkarshabhope
 
Lecture 2 Introduction to AWT (1).ppt.hello
mayurDharmik1
 
Java AWT Controls and methods, Listener classes
muthulakshmi279332
 
Session 9_AWT in java with all demonstrations.pdf
tabbu23
 
AWT New-3.pptx
SarthakSrivastava70
 
Swing component point are mentioned in PPT which helpgul for creating Java GU...
sonalipatil225940
 
Ad

More from Assistant Professor, Shri Shivaji Science College, Amravati (6)

PDF
B.Sc. III(VI Sem) Advance Java Unit2: Appet
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. III(VI Sem) Question Bank Advance Java(Unit:1,2, and 5)
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-2 Relational Model
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-1 Fundamentals of DBMS
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Advance Java Unit2: Appet
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Question Bank Advance Java(Unit:1,2, and 5)
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-2 Relational Model
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-1 Fundamentals of DBMS
Assistant Professor, Shri Shivaji Science College, Amravati
 
Ad

Recently uploaded (20)

PDF
GK_GS One Liner For Competitive Exam.pdf
abhi01nm
 
PPTX
GB1 Q1 04 Life in a Cell (1).pptx GRADE 11
JADE ACOSTA
 
PPTX
Qualification of DISSOLUTION TEST APPARATUS.pptx
shrutipandit17
 
PPTX
Vectors and applications of genetic engineering Pptx
Ashwini I Chuncha
 
PPTX
Different formulation of fungicides.pptx
MrRABIRANJAN
 
PPTX
Clinical trial monitoring &safety monitoring in clinical trials.2nd Sem m pha...
Mijamadhu
 
PDF
Carbon-richDustInjectedintotheInterstellarMediumbyGalacticWCBinaries Survives...
Sérgio Sacani
 
PDF
Adding Geochemistry To Understand Recharge Areas - Kinney County, Texas - Jim...
Texas Alliance of Groundwater Districts
 
PPT
Human physiology and digestive system
S.B.P.G. COLLEGE BARAGAON VARANASI
 
PPTX
Q1 - W1 - D2 - Models of matter for science.pptx
RyanCudal3
 
PPTX
Envenomation AND ANIMAL BITES DETAILS.pptx
HARISH543351
 
PDF
Introduction of Animal Behaviour full notes.pdf
S.B.P.G. COLLEGE BARAGAON VARANASI
 
PDF
NRRM 330 Dynamic Equlibrium Presentation
Rowan Sales
 
PPTX
Akshay tunneling .pptx_20250331_165945_0000.pptx
akshaythaker18
 
PDF
Annual report 2024 - Inria - English version.pdf
Inria
 
PPTX
Lamarckism is one of the earliest theories of evolution, proposed before Darw...
Laxman Khatal
 
PDF
A young gas giant and hidden substructures in a protoplanetary disk
Sérgio Sacani
 
PPTX
MODULE 2 Effects of Lifestyle in the Function of Respiratory and Circulator...
judithgracemangunday
 
PPTX
Cooking Oil Tester How to Measure Quality of Frying Oil.pptx
M-Kube Enterprise
 
PDF
RODENT PEST MANAGEMENT-converted-compressed.pdf
S.B.P.G. COLLEGE BARAGAON VARANASI
 
GK_GS One Liner For Competitive Exam.pdf
abhi01nm
 
GB1 Q1 04 Life in a Cell (1).pptx GRADE 11
JADE ACOSTA
 
Qualification of DISSOLUTION TEST APPARATUS.pptx
shrutipandit17
 
Vectors and applications of genetic engineering Pptx
Ashwini I Chuncha
 
Different formulation of fungicides.pptx
MrRABIRANJAN
 
Clinical trial monitoring &safety monitoring in clinical trials.2nd Sem m pha...
Mijamadhu
 
Carbon-richDustInjectedintotheInterstellarMediumbyGalacticWCBinaries Survives...
Sérgio Sacani
 
Adding Geochemistry To Understand Recharge Areas - Kinney County, Texas - Jim...
Texas Alliance of Groundwater Districts
 
Human physiology and digestive system
S.B.P.G. COLLEGE BARAGAON VARANASI
 
Q1 - W1 - D2 - Models of matter for science.pptx
RyanCudal3
 
Envenomation AND ANIMAL BITES DETAILS.pptx
HARISH543351
 
Introduction of Animal Behaviour full notes.pdf
S.B.P.G. COLLEGE BARAGAON VARANASI
 
NRRM 330 Dynamic Equlibrium Presentation
Rowan Sales
 
Akshay tunneling .pptx_20250331_165945_0000.pptx
akshaythaker18
 
Annual report 2024 - Inria - English version.pdf
Inria
 
Lamarckism is one of the earliest theories of evolution, proposed before Darw...
Laxman Khatal
 
A young gas giant and hidden substructures in a protoplanetary disk
Sérgio Sacani
 
MODULE 2 Effects of Lifestyle in the Function of Respiratory and Circulator...
judithgracemangunday
 
Cooking Oil Tester How to Measure Quality of Frying Oil.pptx
M-Kube Enterprise
 
RODENT PEST MANAGEMENT-converted-compressed.pdf
S.B.P.G. COLLEGE BARAGAON VARANASI
 

B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling

  • 1. 1 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor UNIT-III: AWT & Event Handling * Introduction to AWT *  AWT stands for Abstract Window Toolkit. It is provided in java as a java package i.e. ‘java.awt”  The ‘java.awt’ contains numerous classes and methods that allow us to create and manage window applications.  This AWT package allows a programmer to Create a standard window, dialog box, controls, etc.  In windows, controls are nothing but window element that allow user to interact with your application. For example, Command Button, Scroll Bar, Menu Bar, etc.  The following figure shows the AWT class hierarchy:  Component: o Component is an abstract class; it contains attributes of visual components. o All user interface elements like button, label, checkbox, scrollbar etc. are displayed on the screen are subclasses of class Component. Object Container Panel Applet Wndow Frame Dialog Label Button Checkbox Scrollbar TextComponent TextField TextArea Component 2 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  Container: o Container is a class that defined positioning of controls i.e. layout within the window that we perform in .Net just by drag and drop.  Panel: o This class is used to create panel window, the window not having border, title bar, and menu bar. Ex. Applet window  Frame: o This class is used to create a standard window i.e. having border, title bar and menu bar.  The ‘java.awt’ is one of the java’s largest package.  The following table shows few of the classes defined in ‘java.awt’ package. # Class name Description 1 Frame Creates a standard window that has t title bar, resize corners, and a menu bar. 2 Label Creates a label that displays a string. 3 Button Creates a push button control. 4 Checkbox Creates a checkbox control. 5 TextField Creates a single-line edit control. 6 TextArea Creates a multiline edit control. 7 List Creates a list from which the user can choose.. 8 Scrollbar Creates a scroll bar control. 9 BorderLayout The border layout manager. Border supports five positions on window at which we can place control: North, South, East West, and Center. 10 CardLayout The card layout manager. Card layouts emulate index cards. Only the one on top is showing. 11 FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom. 12 GridLayout The grid layout manager. Grid layout displays components in a two-dimensional grid.
  • 2. 3 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Working with Frame Window *  A frame is thought of as a “window”.  To create a frame window, we have to follow TWO steps: 1. By extending ‘Frame’ class. 2. By creating object of ‘Frame’ class. 1. Creating frame window by extending ‘Frame’ class: 2. Creating frame window By creating object of ‘Frame’ class: import java.awt.*; class MYWINDOW extends Frame { MYWINDOW() { setSize(500,400); setTitle(“My First frame window”) setVisible(true); setLayout(null); // No layout manager(Default: Border Layout } public static void main(String args[]) { MYWINDOW obj= new MYWINDOW(); } } import java.awt.*; class MYWINDOW { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(500,400); obj.setTitle(“My First frame window”) obj.setVisible(true); obj.setLayout(null); // No layout manager(Default: Border Layout } } 4 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  The output of the above both programs is same as shown below: * Label Control *  A label is window element that contains a string, which it displays.  The class ‘Label’ defines the following THREE constructors used to create label control: 1. Label() : This constructor creates a blank label. 2. Label(String str): This constructor creates a label that contains a string ‘str’. This string is Left-justified. 3. Label(String str, int how) :This constructor creates a label that contains a string ‘str’ using alignment ‘how’. The value of ‘how’ must be one of these constants: Label.LEFT, Label.RIGHT or Label.CENTER.
  • 3. 5 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  For example,  The output of the above program is as follows: import java.awt.*; class LABEL { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(null); obj.setTitle("Program on Label control"); Label x=new Label("Enter First Name:"); x.setBounds(40,40,200,30); Label y=new Label("Enter Last Name:", Label.RIGHT); y.setBounds(40,80,200,20); obj.add(x); obj.add(y); } } 6 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Button Control *  A command button is a component that has a label printed over it and generates an event when it is pressed.  The class ‘Button’ defines the following TWO constructors used to create button control: Constructor Prototype Purpose Button (); It creates a blank button. Button (String str); It creates a button that contains a string ‘str’ as button label. For example, import java.awt.*; class BUTTON { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(null); obj.setTitle("Program on Button control"); Button B1=new Button(); B1.setBounds(40,40,100,20); B1.setLabel("OK"); Button B2=new Button("CANCEL"); B2.setBounds(40,70,100,20); obj.add(B1); obj.add(B2); } }
  • 4. 7 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  The output of above program is as follows: * Checkbox Control *  A check box is a component that allow user to select the option. By default they are in square box shape.  A check box control has ‘label’ and ‘state’ these two attributes.  The state of check box is either ‘checked’ or ‘unchecked’.  The class ‘Checkbox’ is defined in ‘java.awt’ package with following THREE types of constructors to create check boxes. Constructor Purpose Checkbox() It creates a check box with blank label. Checkbox(String str) It creates a check box whose label is specified by string ‘str’. Checkbox(String str, boolean X) It creates a check box with label ‘str’ and also allow to set initial state i.e. true or false. 8 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor For example, The output of above program is: NOTE: Here we used layout manager ‘FlowLayout’. So no need to set bounds for control that we are positioning within window. import java.awt.*; class CHECKBOX { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on Checkbox control"); Checkbox c1,c2,c3; c1=new Checkbox(); c2=new Checkbox("Marks Memo"); c3=new Checkbox("TC",true); obj.add(c2); obj.add(c3); obj.add(c1); } }
  • 5. 9 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Text field Control *  A text field is a single line component that allow user to enter strings and to edit the string present in it.  The class ‘TextField’ defines the following FOUR constructors used to create text field control: Constructor Purpose TextField() It creates a blank field of default width of 2 characters. TextField(int n) It creates a text field which is ‘n’ characters wide. TextField(String str) It creates a text field and initializes a string ‘str’ to it. TextField(String str, int n) It creates a text field and initializes a string ‘str’ to it and sets its width to ‘n’ characters. For example, import java.awt.*; class TEXTFIELD { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on text field control"); TextField text1,text2; text1=new TextField(); text1.setText("Hello India"); text1.setEditable(false); text2=new TextField("Hello World"); obj.add(text1); obj.add(text2); } } 10 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor The output of above program is: * Text area Control *  A text area is a component that allow user to enter multiple line of text and to edit.  The class ‘TextArea’ defines the following FIVE constructors used to create text area control: Constructor Purpose TextArea() It creates a default text area control. TextArea(int x, int y) It creates a text area control of ‘x’ number of lines and of width ‘y’ characters. TextArea(String str) It creates a text area and initializes string ‘str’ to it. TextArea(String str, int x, int y) It creates a text area of ‘x’ lines, of width ‘y’ character and initializes string ‘str’ to it. TextArea(String str, int x, int y, int sBars) It creates a text area of ‘x’ lines, of width ‘y’ character and initializes string ‘str’to it having scroll bars specified by ‘sBars’.
  • 6. 11 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor For example, The output of above program is: import java.awt.*; class TEXTAREA { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on text area control"); TextArea TA1,TA2,TA3; TA1=new TextArea(); TA2=new TextArea("Hello Indian Hello World",10,4,TextArea.SCROLLBARS_BOTH); TA3=new TextArea(5,10); obj.add(TA1); obj.add(TA2); obj.add(TA3); } } 12 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * List Control *  The class ‘List’ provides following THREE constructors to create list control.  By default multi-selection property of list control is FALSE. Constructor Purpose List() It creates a list control that allows only one item to be selected at a time with default FOUR rows. List( int numRows) It create a list control and integer ‘numRows’ is number of items in the list that will always be visible. List(int numRows, boolean flag) It creates a list control in which multiple selections are allowed or not is specified by ‘flag’ i.e. boolean value ‘true’ or ‘false’. For example, import java.awt.*; class LIST { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on list control"); List x=new List(); //List X x.add("Udgir"); x.add("Latur"); List y=new List(1); // List Y y.add("Amravati"); y.add("Latur"); y.add("Banglore"); List z=new List(5,true); // List Z z.add("Udgir"); z.add("Amravati"); z.add("Banglore"); obj.add(x); obj.add(y); obj.add(z); } }
  • 7. 13 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor The output of above program is: * Scrollbar Control *  A scrollbar control is used to view the contents of the page which can’t be displayed on screen in one page.  Two types of scrollbars are available i.e. Horizontal and Vertical.  Each scroll bar is assigned with a range of values i.e. ‘Minvalue’ and ‘Maxvalue’(Integers).  A scrollbar consists of several individual parts: Arrows on each end and a slider box(Thumb).  The position of slider box on the scrollbar indicates the current value of the scrollbar.  The class ‘Scrollbar’ provides following THREE constructors to create scrollbar. 14 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor Constructor Purpose Scrollbar() It creates a default vertical scrollbar. Scrollbar(int style) It creates either vertical OR horizontal scrollbar. The ‘style’ can take one of the TWO values Scrollbar.VERTICAL(0) or Scrollbar.HORIZONTAL(1) Scrollbar(int style, int initial, int thumbSize, int min, int max) It creates scrollbar with specified initial value. It also allow to specify Minvalue and Maxvalue. The ‘thumbSize’ determines the width of the slider box. For example, import java.awt.*; class SCROLLBAR { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on scrollbar control"); Scrollbar x=new Scrollbar(); Scrollbar y=new Scrollbar(Scrollbar.HORIZONTAL); Scrollbar z=new Scrollbar(Scrollbar.HORIZONTAL,500,500,0,1000); z.setPreferredSize(new Dimension(200,200)); //Dimension(width,height) y.setPreferredSize(new Dimension(100,200)); //Dimension(width,height) obj.add(x); obj.add(y); obj.add(z); } }
  • 8. 15 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor The output of above program is: * Layout Manager *  Layout means the arrangement of components within the container.  In java, container is nothing but a window.  Positioning controls within the window is handled in java by some classes defined, called Layout Managers.  In java, the following FIVE classes represents different layout managers: 1. java.awt.BorderLayout 2. java.awt.GridLayout 3. java.awt.FlowLayout 4. java.awt.CardLayout 5. java.awt.GridBagLayout 16 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * BorderLayout Manager *  This layout is used to arrange the components in FIVE regions: north, south, east, west and center. Each region(area) may contain only one component.  It is default layout for frame(standard) window.  The BorderLayout class contains following five defined constant’s: o public static final int NORTH o public static final int SOUTH o public static final int EAST o public static final int WEST o public static final int CENTER (Default)  For example, The output of above program is as follows: import java.awt.*; class BORDERLAYOUT { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); obj.setTitle("Program on list control"); BorderLayout mgr=new BorderLayout(); obj.setLayout(mgr); Button b1=new Button("Hello"); Button b2=new Button("World"); Button b3=new Button("Thank you!"); obj.add(b1,BorderLayout.WEST); obj.add(b2,BorderLayout.NORTH); obj.add(b3); // Default CENTER } }
  • 9. 17 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor 18 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * GridLayout Manager *  The grid layout divides the window into rows and columns.  Each cell is referred as a single Grid.  One component is displayed in one grid of the window.  For example, The output of above program is as follows: import java.awt.*; class GRIDLAYOUT { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setTitle("Program on Grid layout manager"); GridLayout mgr=new GridLayout(2,2); obj.setLayout(mgr); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); Button b4=new Button("4"); obj.add(b1); obj.add(b2); obj.add(b3); obj.add(b4); } }
  • 10. 19 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * FlowLayout Manager *  The flow layout is used to arrange the components in a line one after another(in a flow).  It is default layout manager for panel(applet) window.  This layout manager support THREE alignments by defining following integer constants in ‘FlowLayout’ class:  public static fine int LEFT  public static fine int RIGHT  public static fine int CENTER(Default)  For example, The output of above program is as follows: import java.awt.*; class FLOWLAYOUT { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setTitle("Program on flow layout manager"); FlowLayout mgr=new FlowLayout(FlowLayout.RIGHT); obj.setLayout(mgr); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); Button b4=new Button("4"); obj.add(b1); obj.add(b2); obj.add(b3); obj.add(b4); } } 20 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor
  • 11. 21 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * CardLayout Manager *  This layout manager is different among all other layout managers.  This layout manager defines a container and allow to add any number of panel windows containing group of components, but only one panel window can be shown at a given time.  The panel window is referred as a card.  Only one card is shown at a time and other present but hidden below it.  For example, import java.awt.*; class CARDLAYOUT { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setTitle("Program on card layout manager"); CardLayout mgr=new CardLayout(); obj.setLayout(mgr); Panel cricket=new Panel(); //Creating card for CRICKET cricket.add(new Checkbox("Jaques Kallis")); cricket.add(new Checkbox("Virat Kohli")); Panel tennis=new Panel(); // Creating card for TENNIS tennis.add(new Checkbox("Pit Sampras")); tennis.add(new Checkbox("John Edberg")); obj.add(cricket,"X"); // Adding group(card) to container obj.add("Y",tennis); // Addign group(card) to container mgr.show(obj,"Y"); } } 22 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor The output of above program is as follows: * CardLayout Manager *  This layout manager is different among all other layout managers.  This layout manager defines a container and allow to add any number of panel windows containing group of components, but only one panel window can be shown at a given time.  The panel window is referred as a card.  Only one card is shown at a time and other present but hidden below it.
  • 12. 23 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  For example, The output of above program is as follows: import java.awt.*; class CARDLAYOUT { public static void main(String args[]) { Frame obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setTitle("Program on card layout manager"); CardLayout mgr=new CardLayout(); obj.setLayout(mgr); Panel cricket=new Panel(); //Creating card for CRICKET cricket.add(new Checkbox("Jaques Kallis")); cricket.add(new Checkbox("Virat Kohli")); Panel tennis=new Panel(); // Creating card for TENNIS tennis.add(new Checkbox("Pit Sampras")); tennis.add(new Checkbox("John Edberg")); obj.add(cricket,"X"); // Adding group(card) to container obj.add("Y",tennis); // Addign group(card) to container mgr.show(obj,"Y"); } } 24 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Event Delegation Model *  Event Delegation model is mechanism used to perform event handling in Java.  The principles of event delegation model are: 1. A source(component) generates an event and sends it to one or more listeners. 2. The listeners simply waits until it receives an event. Once received, the listener processes the event and then returns. NOTE : Listeners must be registered with a source. 1. Event :  An event is an object of event class that describes a state change in a source.  For example, Event may be generated when button is pressed, item in a list is selected or mouse is clicked. 2. Source :  A source is an object of control (e.g. Label, Button, etc.) that generates an event.  A single source may generate more than one type of events.  A source must be registered with listeners. The general form of registration is:
  • 13. 25 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor Here, ‘add’ and ‘Listener’ are keywords. A ‘Type’ is name of the event. The ‘el’ is reference to event listener. For example, Button b1=new Button(); b1.addActionListener(this); When button ‘b1’ is pressed, notification to listener will be sent. 3. Listener :  A listener is an object that is notified when an event occurs. It has TWO major requirements: 1. It must have been registered with one or more sources to receive notifications about specific event types. 2. It must be implemented to receive and process these notifications.  The methods that can receive and process the events are defined in built-in interfaces.  A single interface has one or more methods declared in it.  For example, ActionListener interface has only one method i.e. ActionPerformed() method but MouseListener interface has multiple methods for different event that mouse can generate. public void addTypeListener(TypeListener el); 26 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Java AWT Events *  Here we will discuss various events that we can handle by using event delegation model in java.  The following table shows various events and corresponding classes defined in ‘java.awt.event’ package whose object is automatically generated when event occurs. Event Event Class whose object is generated Window activated WindowEvent Window closed Window is being closed Window is deactivated Window is de-iconified Window is iconified Window is opened Button pressed ActionEvent Adjustment using scrollbar AdjustmentEvent Control gets focus FocusEvent Control loses focus State of control changed(checkbox) ItemEvent Change occurs in text field or text area TextEvent Mouse button is pressed and released at a time MouseEvent Mouse pointer enters into control Mouse pointer leaves control Mouse Button is pressed Mouse Button is released Mouse dragged MouseMotionEvent Mouse moved
  • 14. 27 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Sources of Event *  Source of the event is the component/control (like, button, checkbox, etc) on which event is occurring.  Particularly, in a java program an object of component/control is a source of an event.  The following table shows the various event and possible sources of the event. Event Sources of Event Window activated A panel or frame window Window closed Window is being closed Window is deactivated Window is de-iconified Window is iconified Window is opened Button pressed A Button Adjustment using scrollbar Scrollbar Control gets focus Any Control Control loses focus State of control changed(checkbox) Checkbox, radio button Change occurs in text field or text area Text field or Text area Mouse button is pressed and released at a time Any Control Mouse pointer enters into control Mouse pointer leaves control Mouse Button is pressed Mouse Button is released Mouse dragged Input device mouse Mouse moved 28 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Event Listener Interface * In java number of interfaces defined that contain methods to handle the generated events. Hence these interfaces are also called event handlers. For each event class there is its corresponding listener interface is defined in “java.awt.event” package. The following table shows event class and associated listener interface names. Event Class Listener Interface WindowEvent WindowListener MouseEvent MouseListener MouseMotionEvent MouseMotionListener FocusEvent FocusListener ActionEvent ActionListener AdjustmentEvent AdjustmentListener ItemEvent ItemListener TextEvent TextListener  A single listener interface defined with one or more abstract methods to handle different events as described below: Abstract methods declared in interface WindowListener Method Purpose windowActivated() invoked when a window is activated. windowDeactivated() Invoked when window is deactivated windowClosing() Invoked when window is being closed. windowOpened() Invoked when window is get opened. windowIconified() Invoked when window is iconified. windowDeiconified() Invoked when window is de-iconified. windowClosed() Invoked when widow is closed.
  • 15. 29 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor Abstract methods declared in interface MouseListener Method Purpose mouseCliked() Invoked when mouse is pressed and released at a same time mousePressed() Invoked when mouse button is pressed. mouseReleased() Invoked when mouse button is released. mouseEntered() Invoked when mouse pointer enters into control. moueseExited() Invoked when mouse pointer leaved control. Abstract methods declared in interface MouseMotionListener Method Purpose mouseDragged() Invokes multiple times as the mouse is dragged. mouseMoved() Invokes multiple times as the mouse is moved. Abstract methods declared in interface FocusListener Method Purpose focusGained() Invoked when control gets keyboard focus. focusLost() Invoked when control loses keyboard focus. Abstract methods declared in interface ActionListener Method Purpose actionPerformed() Invoked when button control is pressed. Abstract methods declared in interface AdjustmentListener Method Purpose adjustmentValueChanged() Invoked when user scrolling using scrollbar button. Abstract methods declared in interface ItemListener Method Purpose itemStateChanged() Invoked when state of the checkbox/radio button changed. Abstract methods declared in interface TextListener Method Purpose itemStateChanged() Invoked when state of the checkbox/radio button changed. 30 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Adapter Classes *  To handle event, we have to implement the interfaces defined as listeners.  We know that when an interface is implemented all the abstracts methods of that interface must be defined in a class which is implementing it.  A listener interface may contain multiple abstract methods.  We cannot implement an interface by defining few of the methods of the interface rather we have to define all the abstract methods of that interface.  Java provides special classes called Adapter classes, that we can use to handle only some of the events by implementing only those methods that we require to handle the events.  For example, The interface FocusListener has two methods to handle two events i.e. focusGained() and focusLost(). If we want to handle only one event, then by using adapter class associated with FocusListener interface we can implement only one of these two methods.  The following table shows the adapter classes provided in Java and its associated interface listener: Adapter Class Listener Interface WindowAdapter WindowListener FocusAdapter FocusListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener
  • 16. 31 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor For example,  In above code, we are implementing FocusListner interface which has two abstract methods i.e. focusGained() and focusLost().  This code will produce error that implementation of focusLost() method is missing. That means we must define both abstract methods while implementing FocusListener interface. Although we don’t want handle focus lost event.  This problem will be resolved by using adapter class FocusAdapter as shown in following program. import java.awt.*; import java.awt.event.*; public class test implements FocusListener { Frame obj; public static void main(String args[]) { test x=new test(); } test() { obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); TextField t1=new TextField(); obj.add(t1); Button b1=new Button("red"); obj.add(b1); b1.addFocusListener(this); } // Only focusGained event we want handle public void focusGained(FocusEvent z) { obj.setBackground(Color.RED); } } 32 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor  The error occurred in previous programs is removed in this code by using FocusAdapter Class instead of FocusListener interface. import java.awt.*; import java.awt.event.*; public class test extends FocusAdapter { Frame obj; public static void main(String args[]) { test x=new test(); } test() { obj=new Frame(); obj.setSize(400,300); obj.setVisible(true); obj.setLayout(new FlowLayout()); TextField t1=new TextField(); obj.add(t1); Button b1=new Button("red"); obj.add(b1); b1.addFocusListener(this); } // Only focusGained event we want handle public void focusGained(FocusEvent z) { obj.setBackground(Color.RED); } }
  • 17. 33 B.Sc. III (VI Sem) Advance Java Programming (Unit-III) Prepared by, Mr. Hushare Y.V., [M.Sc., MCA, SET], Asst. Professor * Inner Class *  Inner classes are a security mechanism in Java.  We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private.  Creating an inner class is quite simple. You just need to write a class within a class. In the given example, we make the inner class private and access the class through a method. Output: This is inner class class Outer_Demo { int num; private class Inner_Demo // inner class { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class innerclass { public static void main(String args[]) { Outer_Demo outer = new Outer_Demo(); outer.display_Inner(); } }