UNIT-5 OOP Lecture Notes
UNIT-5 OOP Lecture Notes
➢API (Application Programming Interface), it ➢ Graph ics and imaging tools, including
is a collection of classes, interfaces, and
shapes, colour, and font classes.
subpackages helps to develop the program.
➢Java AWT components are platform- ➢ Layout managers, for flexible window layouts
AWT API such as TextField, Label, TextArea, the native platform clipboard.
RadioButton, CheckBox, Choice, List etc.
1
AWT Class Hierarchy
6
Build GUI using AWT
Steps :
➢ Create Container such as Frame or Dialog (for an application), or an Applet (for web
➢ Create some Components, such as Button, TextField, List, Panels, etc. by creating an
7
Methods of Component Class
8
Working with Frame (Container)
Frame :
▪ void setSize(int newWidth, int newHeight) -
➢ In Java, most of the AWT applications are
size of the window is specified by newWidth
created using Frame window.
and newHeight. The dimensions are specified
➢ Frame class has two different constructors,
in terms of pixels.
▪ Frame() – This form creates a standard
▪ Dimension getSize() - This method returns
window that does not contain a title.
the current size of the window contained
▪ Frame(String title) - This form creates a
within the width and height fields of a
window with the title specified by title.
Dimension object.
1. Creating a Frame : There are two ways to
3. Hiding and Showing a Window
create a GUI using Frame in AWT.
▪ void setVisible(boolean visibleFlag) - After a
▪ By Instantiating Frame class
frame window has been created, it will not be
▪ By extending Frame class
visible until you call setVisible().
2. Setting the Window’s Dimensions : It must
▪ The component is visible if the argument to
be set the size of the window after it has been
this method is true. Otherwise, it is hidden.
created.
9
I. Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class Testawt
{
public Testawt()
{
Frame fm=new Frame(“GUI from LBRCE-CSE-A”);
//Creating a frame
Label lb = new Label("welcome to Java AWT Class");
//Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
10
II. Creating Frame Window by Extending Frame class
import java.awt.*;
public class Testawt1 extends Frame
{
public Testawt1()
{
setTitle("LBRCE-CSE-B"); //setting title.
➢ Closing the AWT Window or Frame can be done by calling dispose() or System.exit(0)
WindowAdapter class.
12
I. By inheriting WindowAdapter class
import java.awt.*;
import java.awt.event.*;
public class Testawtc extends WindowAdapter
{
Testawtc()
{
Frame fm=new Frame("GUI from LBRCE-CSE-A");
15
Working with Panel (Container)
Panel :
▪ Panel is a window that does not contains a Panel p2=new Panel();
p2.setBackground(Color.blue);
title bar, menu bar and borders. Label lb2 = new Label("Panel 2 Blue");
▪ Other components like button, textfields etc. p2.add(lb2);
Button bt2 = new Button("Button 2");
can be added to Panel object by it add() p2.add(bt2);
add(p2);
method. }
Example : }
public class SamplePanel
import java.awt.*;
{
class SampleJavaPanel extends Frame
public static void main(String[] args)
{
{
SampleJavaPanel()
SampleJavaPanel panelframe = new
{
SampleJavaPanel();
setLayout(new FlowLayout());
Panel p1 = new Panel();
panelframe.setTitle("Java AWT Panels Example");
p1.setBackground(Color.red);
panelframe.setSize(500,300);
Label lb1 = new Label("Panel 1 Red");
panelframe.setVisible(true);
p1.add(lb1);
}
Button bt1 = new Button("Button 1");
}
p1.add(bt1);
add(p1);
16
Working with Panel (Container) - Output
17
setBounds() Method
18
Panel with setBounds() Method - Example
import java.awt.*; Panel p2=new Panel();
class SampleJavaPanel extends Frame p2.setBackground(Color.blue);
{ p2.setBounds(350,100,200,50);
SampleJavaPanel()
{ add(p2);
setTitle("Java AWT Panels Example"); Label lb2 = new Label("Panel 2 Blue");
setSize(800,400);
setVisible(true); p2.add(lb2);
setLayout(null); Button bt2 = new Button("Button 2");
20
Working with Dialog (Container)
import java.awt.*;
Dialog : public class SampleDialog
▪ The Dialog control represents a top-level {
public static void main(String[] args)
window with a border and a title used to take {
Frame frame = new Frame("Java AWT Dialog
some form of input from the user.
Example");
▪ It inherits the Window class. frame.setLayout(new FlowLayout());
frame.setSize(400, 400);
▪ Unlike Frame, it doesn't have maximize and frame.setBackground(Color.white);
frame.setVisible(true);
minimize buttons.
Dialog d1 = new Dialog(frame,"Java Dialog
Example", true);
Constructor : d1.setLayout(new FlowLayout());
d1.setSize(400, 200);
Dialog(Frame owner, String title, boolean d1.setBackground(Color.gray);
model)
Button bt1 = new Button("Button!!");
Constructs an initially invisible Dialog with the bt1.setSize(20,10);
d1.add(bt1);
specified owner Frame, title and modality. d1.setVisible(true);
}
}
21
Working with Dialog (Container) - Output
22
AWT Components
➢ A Component is an object with a graphical representation that can be displayed on the screen and
➢ The Component class is the base and abstract parent of the nonmenu-related AWT components.
1. Button (java.awt.Button)
▪ To create a Button object, simply create an instance of the Button class by calling one of the
constructors. The most used constructor of the Button class takes a String argument, that gives
▪ When a user presses on a Button object an event is generated. The label of the button that is
2. Checkboxes (java.awt.Checkbox)
▪ Checkboxes are two states, on and off. The state of the button is returned as the Object
▪ To find out the state of a checkbox object we can use getState() that returns a true or
false value.
▪ To find the label of the checkbox using getLabel() that returns a String object.
Constructor:
Checkbox(String, boolean)
f.add(cb1);
f.add(cb2);
f.add(cb3);
}
public static void main(String[] ar) {
SampleCheckbox sc = new SampleCheckbox();
} }
26
3. Radio Buttons (java.awt.CheckboxGroup)
▪ Exactly one check box button in a CheckboxGroup can be in the "on" state at any
given time. Pushing any button sets its state to "on" and forces any other button that is
▪ The following code example produces a new check box group, with three check boxes:
CheckboxGroup cbg = new CheckboxGroup();
add(new Checkbox("one", cbg, true));
add(new Checkbox("two", cbg, false));
add(new Checkbox("three", cbg, false));
27
3. Radio Buttons (java.awt.CheckboxGroup) - Example
public class CheckboxGroupDemo
{
CheckboxGroupDemo() {
Frame ck_groupf= new Frame("CheckboxGrouping"); Output:
CheckboxGroup obj = new CheckboxGroup();
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.add(ckBox3);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[]) {
new CheckboxGroupDemo(); }
}
28
4. Choice Buttons (java.awt.Choice)
▪ Choice Buttons displays a selection; however, it requires less space and allows us to add items to
the menu dynamically using the addItem() or add() method.
import java.awt.*; Button bt1= new Button("Submit");
public class SampleChoice f.add(lb1);
{ f.add(ch);
SampleChoice() f.add(bt1);
{ }
Frame f = new Frame("Java AWT Choice public static void main(String[] ar) {
Example"); SampleChoice sl = new SampleChoice();
f.setLayout(new FlowLayout()); }
f.setBackground(Color.lightGray); }
f.setSize(300,300);
f.setVisible(true);
▪ Creates a list with n items in the list. Specify the “n” elements in the constructor space and
allows us to add elements to the list using the add() method ONLY.
public class SampleList Button bt1= new Button("Submit");
{
SampleList() f.add(lb1);
{ f.add(list);
Frame f = new Frame("Java AWT Choice f.add(bt1);
Example"); }
f.setLayout(new FlowLayout()); public static void main(String[] ar) {
f.setBackground(Color.lightGray); SampleList sl = new SampleList();
f.setSize(300,300); }
f.setVisible(true); }
Label lb1 = new Label("Select your country from
the Menu: ");
6. TextFields (java.awt.TextField)
▪ We can make this textfield read-only or editable. We can use the setEditable(false) to
31
6. TextArea (java.awt.TextArea)
32
6. TextArea (java.awt.TextArea) - Example
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to Java
Programming",30,5,TextArea.SCROLLBARS_BOTH
);
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
33
AWT Component - Example
import java.awt.*;
import java.awt.event.*; Choice choice = new Choice();
public class ComponentExam extends WindowAdapter choice.addItem("Choice Item 1");
{ choice.addItem("Choice Item 2");
ComponentExam() choice.addItem("Choice Item 3");
{ fm.add(choice);
Frame fm = new Frame("Example of Multiple
Components"); Label l = new Label("Test Label");
fm.setSize(600,300); fm.add(l);
fm.setVisible(true);
fm.setLayout(new FlowLayout()); TextField t = new TextField("Test TextField",30);
fm.addWindowListener(this); fm.add(t);
}
Button b = new Button("Test Button");
fm.add(b); public void windowClosing(WindowEvent e)
{
Checkbox cb = new Checkbox("Test System.exit(0);
Checkbox"); }
fm.add(cb); public static void main(String args[])
{
CheckboxGroup cbg = new CheckboxGroup(); ComponentExam CE = new ComponentExam();
fm.add(new Checkbox("CB Item 1", cbg, false)); }
fm.add(new Checkbox("CB Item 2", cbg, false)); }
fm.add(new Checkbox("CB Item 3", cbg, true));
34
AWT Component - Output
35
7. Canvas (java.awt.Canvas)
▪ Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user
▪ The canvas is used to provide a place to draw using mouse pointer. We can use it to get
configuration.
36
7. Canvas (java.awt.Canvas)
37
7. Canvas (java.awt.Canvas) - Example
39
8. MenuItem and Menu
➢ The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem.
➢ The object of Menu class is a pull-down menu component which is displayed on the
menu bar. It inherits the MenuItem class.
Steps:
1. Create a Menu bar object under MenuBar class and attach that to a container frame
using setMenuBar().
2. Create a Menu (fields to be displayed on Menu Bar) using object of Menu class and
attach them to the bar.
3. Use the MenuItem class to create Menu items belongs to a particular Menu in the
MenuBar.
Note: Sub Menu’s created as Menu Items and attach them to Menu.
40
8. MenuItem and Menu - Example
class MenuDemo1 {
sub_menu1.add(b1);
MenuDemo1() {
sub_menu1.add(b2);
Frame menu_f= new Frame("LBRCE-CSE-A Menu
sub_menu1.add(b3);
and MenuItem Demo");
sub_menu1.add(b4);
menu_f.setSize(400,400);
Menu menu12 = new Menu("File (Shapes) ");
menu_f.setLayout(null);
menu_f.setVisible(true); Menu sub_menu12=new Menu("Sub Menu" );
//Create a Menu bar and set it to frame MenuItem x1=new MenuItem("Oval");
MenuBar menu_bar = new MenuBar(); MenuItem x2=new MenuItem("Rectangle");
menu_f.setMenuBar(menu_bar);
menu12.add(sub_menu12);
Menu menu11 = new Menu("File (Colors) ");
menu12.add(x1);
menu12.add(x2);
MenuItem a1=new MenuItem("Red");
menu_bar.add(menu12);
MenuItem a2=new MenuItem("Green");
Menu sub_menu1=new Menu("Sub Menu" ); MenuItem y1=new MenuItem("Circle");
MenuItem y2=new MenuItem("Round");
menu11.add(a1); MenuItem y3=new MenuItem("Square");
menu11.add(a2);
menu11.add(sub_menu1); sub_menu12.add(y1);
menu_bar.add(menu11); sub_menu12.add(y2);
MenuItem b1=new MenuItem("Light Red"); sub_menu12.add(y3);
MenuItem b2=new MenuItem("Drak Red"); }
MenuItem b3=new MenuItem("Light Green"); public static void main(String args[]) {
MenuItem b4=new MenuItem("Dark Green"); new MenuDemo1(); } }
41
8. MenuItem and Menu - Output
42
9. PopupMenu (java.awt.PopupMenu)
➢ PopupMenu can be dynamically popped up at specific position within a component. It inherits
the Menu class.
import java.awt.*;
import java.awt.event.*;
class PopupMenuDemo1 pop_menu.add(pop_cut);
{ pop_menu.add(pop_copy);
PopupMenuDemo1() pop_menu.add(pop_paste);
{
Frame pop_menuf= new Frame("LBRCE pop_menuf.addMouseListener(new MouseAdapter()
==>PopupMenu Demo"); {
pop_menuf.setSize(400,400); public void mouseClicked(MouseEvent a)
pop_menuf.setLayout(null); {
pop_menuf.setVisible(true); pop_menu.show(pop_menuf , a.getX(), a.getY());
}
PopupMenu pop_menu = new PopupMenu("*Edit*"); });
pop_menuf.add(pop_menu);
MenuItem pop_cut = new MenuItem("Cut"); }
pop_cut.setActionCommand("Cut"); public static void main(String args[])
{
MenuItem pop_copy = new MenuItem("Copy"); new PopupMenuDemo1();
pop_copy.setActionCommand("Copy"); }
}
MenuItem pop_paste = new MenuItem("Paste");
pop_paste.setActionCommand("Paste"); 43
9. PopupMenu (java.awt.PopupMenu)
44
Unit- 5 – AWT – Layout Manager
➢ The layout will specify the format or the order in ➢ Whenever a container is resized (or sized for the
which the components have got to be placed on the primary time), the layout manager is employed to
➢ Layout Manager is responsible to rearrange the ➢ The setLayout( ) method has the subsequent
➢ If no call to setLayout( ) is formed, then the default ➢ Then the form and position of every sets
1
Types of Layout Managers - BorderLayout
1. Border Layout :
➢ This layout will display the components along the border of the container.
➢ This layout contains five locations where the component can be displayed.
➢ Locations are North, South, East, west, and Center. The default region is the center.
➢ The above regions are the predefined static constants belongs to the BorderLayout class.
➢ Whenever if other regions’ spaces are not in use automatically container selects as a center region
default and component occupies surrounding region’s spaces of the window and that damages look
2
1. java.awt.BorderLayout
➢ The border layout provides a collection of public static final int NORTH: The North layout
➢ The regions discussed here identified by a public static final int SOUTH: The South layout
F.add(b1,BorderLayout.NORTH);
F.add(b2,BorderLayout.SOUTH);
F.add(b3,BorderLayout.EAST);
F.add(b4,BorderLayout.WEST);
F.add(b5);
}
4
BorderLayout Constructors
2. BorderLayout (int hgap, int vgap)
BorderLayout (int hgap, int vgap) is also written as BorderLayout (int, int) is used to create a border layout with
the given horizontal (hgap) and vertical (vgap) gaps or spaces between the components.
public class borderlayout_spaces public static void main(String[] args)
{
public borderlayout_spaces() {
{
new borderlayout_spaces();
Frame F = new Frame("BorderLayout with Spaces");
F.setSize(400,300); }
F.setVisible(true); }
F.setLayout(new BorderLayout(20,30));
F.setBackground(Color.green);
Constructors in FlowLayout
➢ FlowLayout is one of AWT’s layout managers used
1.FlowLayout(): Constructs an instance of FlowLayout as
to arrange the components in a manner from left to
center-aligned and with 5 pixels gap between the
right, just like words in a paragraph.
components.
➢ When no. of components increases than the window
2.FlowLayout(int align): Constructs a
size, then by default, Java enables FlowLayout to FlowLayout with a given alignment with 5 pixels gap
arrange the components to fit in the windowpane. between the components.
➢ FlowLayout is the default layout provided by layout 3.FlowLayout(int align, int horizontalGap,
int verticalGap): Constructs a FlowLayout with a given
manager for Panel. And BorderLayout is default for
alignment and with a given horizontal and vertical gap
Frame, Dialog containers.
between the components.
➢ FlowLayout uses some default settings such as center ➢This constructor will align by the specified align field as
alignment with five pixels gaps between components RIGHT, LEFT or CENTER and also provides the option for
horizontally and vertically. adding horizontal gap and the vertical gap between
components.
6
FlowLayout Example-1
import java.awt.*; frame1.add(box8); frame1.add(box9); frame1.add(box10);
public class FlowDemo1 frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
{
FlowDemo1() frame1.setSize(200,200); frame1.setVisible(true);
{ }
Frame frame1=new Frame(); public static void main(String[] args) { new FlowDemo1(); }
}
Button box1=new Button("1");
Button box2=new Button("2");
Button box3=new Button("3");
Button box4=new Button("4");
Button box5=new Button("5");
Button box6=new Button("6");
Button box7=new Button("7");
Button box8=new Button("8");
Button box9=new Button("9");
Button box10=new Button("10");
frame1.add(box1);
frame1.add(box2);
frame1.add(box3); 7
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
FlowLayout Example-2
import java.awt.*; public static void main(String[] args)
public class FlowLayoutDemo {
{
FlowLayoutDemo () new FlowLayoutDemo ();
{ }
Frame f = new Frame("FlowLayout for CSE-A"); Label l1 =
new Label ("Enter UserId"); TextField tf1 = new TextField }
(30);
Label l2 = new Label ("Password "); TextField tf2
= new TextField (30); Button b1 = new Button ("SUBMIT");
f.add (l1);
f.add (tf1);
f.add (l2);
f.add (tf2);
f.add (b1);
f.setLayout(new
FlowLayout(FlowLayout.CENTER, 30 ,20));
f.setSize (400, 250);
f.setVisible (true);
f.setBackground(Color.white);
}
8
3. java.awt.GridLayout
Constructors in GridLayout
➢ GridLayout divides the container into a grid
1. GridLayout() - Empty constructor with one column per
of cells called rows and columns.
component in a single row.
➢ It arranges the components in a rectangular grid.
2. GridLayout(int rows, int columns)-
➢ Each cell can accommodate only one
Constructor with a specified number of rows and
component, equally sized and equi-spaced with each
columns.
other.
▪ rows - the number of rows (value zero meaning
➢ According to Grid Layout Manager, the grid cannot
any number of rows).
be empty.
▪ columns - the number of columns (value zero meaning
➢ The default value of the
any number of columns).
ComponentOrientation property is that the
3. GridLayout(int rows, int columns,
orientation of the components is horizontal and
int horizontal gap, int vertical gap)
left-to-right.
▪ horizontal gap- between each of the columns
▪ vertical gap- between each of the rows
9
GridLayout Example-1
public class GridLayoutDemo
{
public static void main(String[] args)
{
Frame frame = new Frame("Grid Layout for CSE-A");
frame.setVisible(true);
frame.setSize(200,200);
panel.setComponentOrientation(ComponentOrientation.LEFT
_TO_RIGHT);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
frame.add(panel);
}} 10
GridLayout Example-2
public class GridLayoutDemo Panel p3 = new Panel ();
{ p3.setBackground(Color.blue);
GridLayoutDemo() f1.add (p3);
{
Frame f1 = new Frame("Grid of Different panel"); f1.setSize Label l2 = new Label ("Welcome to Java");
(250, 250); f1.add (l2);
f1.setVisible (true);
GridLayout ob = new GridLayout (2, 2); }
f1.setLayout (ob); public static void main (String[]args)
{
Panel p1 = new Panel (); new GridLayoutDemo();
p1.setBackground(Color.MAGENTA); }
}
Label l1 = new Label ("Enter name");
TextField tf = new TextField (10);
Button b1 = new Button ("Submit");
p1.add (l1);
p1.add (tf);
p1.add (b1);
f1.add (p1);
➢ In GridLayout manager there is not grid control i.e., inside a grid we cannot align the component in a specific
position.
➢ To overcome this problem, we have an advanced Layout Manager i.e., Grid Bag Layout Manager.
➢ This layout is the most efficient layout that can be used for displaying components. In this layout, we can specify
the location, size, of the components inside of the Grid.
➢ In this Layout manager, for each grid, we need to define grid properties or constraints.
➢ Based on grid properties, the layout manager aligns a component on the grid, and we can span multiple grids also
as per the requirement.
➢ Grid properties are defined using GridBagConstraints class. Each component in a GridBagLayout has its own
set of constraints, so you must associate an object of type.
➢ GridBagConstraints with each component before adding component to the container.
Creation of GridBagLayout:
GridBagLayout gbl = new GridBagLayout();
12
4. java.awt.GridBagLayout
In GridBagLayout, specify the location (or) the size with the help of GridBagConstraints.
Properties of GridBagConstraints:
Variable Role
These contain the coordinates of the origin of the grid i.e., specifying grid location.
gridx and gridy
For defining the number of grids to span a document. Define how many cells will
gridwidth, gridheight
occupy component (height and width). by The default is 1.
Defines the fate of a component smaller than the grid cell. GridBagConstraints.NONE
retains the original size: Default GridBagConstraints.HORIZONTAL expanded
horizontally GridBagConstraints.VERTICAL
fill GridBagConstraints.BOTH expanded vertically expanded to the dimensions of the cell
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0; 15
gc.gridy = 0; f1.add
(b1, gc);
gc.gridx = 1;
gc.gridy = 0;
f1.add (b2, gc);
5. java.awt.CardLayout
➢ Unlike other layouts, the card layout will display the components of a container one at a time.
➢ Card Layout, as the name indicates, works like a deck of playing cards with only one card, i.e.,
the topmost card visible at a single time.
➢ It treats every component in a container as a Card, and the container acting as a Stack of cards.
➢ The ordering of the cards in a container is defined internally. When the container is displayed for the first time, it
is the first component present in the container that is visible at that time.
add(“Cardname”, Component);
Methods of CardLayout
1.first(Container): It is used to flip to the first card of the given container. 2.last(Container): It is used
to flip to the last card of the given container. 3.next(Container): It is used to flip to the next card of the
given container.
5.show(Container, cardname): It is used to flip to the specified card with the given name.
17
CardLayout Example-1
import java.awt.*; import class CardLayoutJavaExample
java.awt.event.*; {
class CardLayoutExample extends Frame implements public static void main(String args[])
ActionListener {
{ CardLayoutExample frame = new
CardLayout card = new CardLayout(10,10); CardLayoutExample();
CardLayoutExample() frame.setTitle("CardLayout in Java Example");
{ frame.setSize(220,150);
setLayout(card); frame.setResizable(false);
Button Btnfirst = new Button("first "); Button frame.setVisible(true);
BtnSecond = new Button ("Second"); Button }
BtnThird = new Button("Third"); }
add(Btnfirst,"Card1");
add(BtnSecond,"Card2");
add(BtnThird,"Card3");
Btnfirst.addActionListener(this);
BtnSecond.addActionListener (this);
BtnThird.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
card.next(this);
} }
18
Unit- 5 – Event Handling
Event Classification of Events :
➢ An event can be defined as changing the state 1. Foreground Events
of an object or behavior by performing actions. ➢ Events that require user interaction to
➢ Activities that cause events to be generated generate, i.e., events are generated due to
are pressing a button, entering a character via interaction by the user on components in
the keyboard, selecting an item in a list, and GUI.
clicking the mouse. ➢ Interactions are nothing but clicking on a
➢ The java.awt.event package can be used to button, scrolling the scroll bar, cursor
provide various event classes. moments, etc.
2. Background Events
➢ Events that don’t require interactions of
users to generate are known as background
events. Examples of these events are
operating system failures/interrupts,
operation completion, etc. 1
Event Handling
➢ It is a mechanism to control the events and to decide what should happen after an
event occur.
➢ To handle the events, Java follows the Delegation Event model.
2
Delegation Event model
3
Registering the Source With Listener
➢ A source must register listeners in order to receive the notifications about specific type
of event.
➢ Each type of event has its own registration method.
➢ Here is the general form:
public void addTypeListener (TypeListener el )
➢ Here, Type is the name of the event, and el is a reference to the event listener.
➢ For example, the method that registers a keyboard event listener is called
addKeyListener( ).
➢ A source must also provide a method that allows a listener to unregister an interest in
a specific type of event.
➢ The general form of such a method is :
public void removeTypeListener(TypeListener el )
4
Event Classes and Listener Interfaces
➢ The java.awt.event package provides many event classes and Listener interfaces for event
handling.
➢ The class AWTEvent, defined within the java.awt package, is the superclass of all AWT-based
events used by the delegation event model.
➢ Its getID( ) method can be used to determine the type of the event. int getID( )
➢ The package java.awt.event defines many types of events that are generated by various user
interface elements.
6
Flow of Event Handling
listener.
7
I. ActionEvent Class
➢ The ActionEvent class defines four integer constants that can be used to identify any
➢ ActionEvent constructors:
➢ You can obtain the command name for the invoking ActionEvent object by using the
➢ String getActionCommand( ) -Returns the command string associated with this action
8
I. ActionListener Interface
➢ The Java ActionListener is notified whenever you click on the button or menu item.
➢ It is notified against ActionEvent.
➢ The ActionListener interface is found in java.awt.event package.
➢ It has only one method: actionPerformed().
➢ The actionPerformed() method is invoked automatically whenever you click on the registered
component.
How to write ActionListener :
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here }
9
ActionListener Example
import java.awt.*;
//3rd step
import java.awt.event.*;
public void actionPerformed(ActionEvent e)
//1st step
{
public class ActionListenerExample
tf.setText("Welcome to LBRCE-CSE-A.");
implements ActionListener{
}
TextField tf;
public static void main(String[] args)
ActionListenerExample()
{
{
new ActionListenerExample();
Frame f=new Frame("ActionListener
}
Example");
}
tf=new TextField();
tf.setBounds(50,50, 200,30);
Button b=new Button("Click Here");
b.setBounds(50,100,60,40);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setBackground(Color.MAGENTA);
}
10
ActionListener Example
f.add(b);f.add(tf);
f.setSize(400,400);
mport java.awt.*;
f.setLayout(null);
import java.awt.event.*;
f.setVisible(true);
public class ActionListenerExample
f.setBackground(Color.GRAY);
{
}
public static void main(String[] args)
}
{
Frame f=new Frame("ActionListener
Example");
final TextField tf=new TextField();
tf.setBounds(100,50, 200,20);
Button b=new Button("Click Here");
b.setBounds(100,100,60,30);
tf.setBackground(Color.green);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to LBRCE-CSE-A");
}
});
11
II. MouseEvent Class
➢ The MouseEvent class defines the following integer constants that can be used to
identify them:
➢ Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their
➢ There are three types of key events, which are identified by these integer constants:
➢ The first two events are generated when any key is pressed or released.
➢ The last event occurs only when a character is generated. Remember, not all key presses
result in characters. For example, pressing shift does not generate a character.
➢ There are many other integer constants that are defined by KeyEvent.
➢ For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers and letters. getKeyCode() is used to get the ASCII code of letters.
16
III. KeyListener Interface
➢ The Java KeyListener is notified whenever you change the state of key.
➢ The KeyListener interface is found in java.awt.event package, and it has three methods.
1. public abstract void keyPressed (KeyEvent e); - It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent e); - It is invoked when a key has been released.
3. public abstract void keyTyped (KeyEvent e); - It is invoked when a key has been typed.
17
KeyListener Example - 1
import java.awt.*;
import java.awt.event.*;
setSize (400, 400);
public class KeyListenerExample1 extends Frame
setLayout (null);
implements KeyListener{
setVisible (true);
}
Label l1,l2;
public void keyPressed(KeyEvent e) {}
TextArea area;
public void keyReleased (KeyEvent e)
KeyListenerExample1()
{
{
String text = area.getText();
l1=new Label("*Enter Some Text Below to Get
String words[] = text.split (" ");
Response*");
l2.setText ("Words: " + words.length + "
l1.setBounds(50,0,300,100);
Characters:" + text.length());
l2 = new Label();
}
l2.setBounds (20, 100, 200, 20);
public void keyTyped(KeyEvent e) {}
area = new TextArea();
area.setBounds (20, 120, 300, 300);
public static void main(String[] args)
{
area.addKeyListener(this);
new KeyListenerExample1();
add(l1);
}
add(l2);
}
add(area);
18
KeyListener Example - 2
Program to demonstrate the KeyListener with texts displaying on certain Key events along
with the key code.
public void keyPressed(KeyEvent ev)
import java.awt.*;
{
import java.awt.event.*;
s= "Event : Key " + ev.getKeyCode() + " is pressed ";
public class KeyListenerExample2 implements
lbl2.setText(s);
KeyListener
}
{
Label lb1, lbl2;
public void keyReleased(KeyEvent ev)
TextField tf1;
{
Frame fr;
s=s+" Event : Key Released ";
String s;
lbl2.setText(s);
KeyListenerExample2() {
fr.setVisible(true);
fr = new Frame("KeyEventListener Example");
}
lb1= new Label(" Key Events will be displayed based
on the actions", Label.CENTER);
public void keyTyped(KeyEvent ev)
lbl2= new Label();
{
tf1 = new TextField(20);
s=s+" Event : Key Typed ";
fr.setLayout(new FlowLayout());
lbl2.setText(s);
fr.add(lb1);
fr.setVisible(true);
fr.add(tf1);
}
fr.add(lbl2);
public static void main(String[] args) {
tf1.addKeyListener(this);
new KeyListenerExample2(); }
fr.setSize(460,250); fr.setVisible(true); }
}
19
IV. WindowEvent Class
➢ The WindowEvent class defines integer constants that can be used to identify different
types of events:
20
IV. WindowListener Interface
➢ Java WindowListener is notified whenever you change the state of window. It is notified against
WindowEvent.
➢ The WindowListener interface is found in java.awt.event package. It has seven methods.
➢ If user defined class inherits the adapter class, then the user defined class does not need to
modify (or overrides) all the methods of the interface, so it reduces code.
➢ As the WindowListener interface contains seven methods. Whenever we need to use this interface,
we must modify or implement all 7 methods. So, when we use the Adapter class (in other words
WindowAdapter) we don't need to modify all the methods, since all the methods are already
modified in it. We only need to implement those methods that are modified.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
25
WindowAdapter Example - 1
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterEx extends Frame
{
public WindowAdapterEx()
{
WindowAdapterClose clsme = new WindowAdapterClose();
addWindowListener(clsme);
Label l = new Label("*Sample Window for Demonstrate
WindowAdapter - Window Closing*");
add(l);
setTitle("WindowAdapter frame closing");
setSize(400, 400);
setVisible(true);
}
public static void main(String args[])
{
new WindowAdapterEx();
}
}
class WindowAdapterClose extends WindowAdapter {
public void windowClosing(WindowEvent e)
{
System.exit(0);
} } 26
WindowAdapter Example - 2
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo
{
// Components - Properties
Frame mainFrame;
headerLabel = new Label("Listener in action:
Label headerLabel;
KeyAdapter");
Label statusLabel;
headerLabel.setAlignment(Label.CENTER);
Panel controlPanel;
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
AwtAdapterDemo()
statusLabel.setSize(350,100);
{
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
// Container - Frame Properties
mainFrame = new Frame("Java AWT Examples");
// Adding of Components to Frame
mainFrame.setSize(400,400);
mainFrame.add(headerLabel);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
//WindowAdapter
mainFrame.addWindowListener(new
// Visiblity of frame
WindowAdapter() {
mainFrame.setVisible(true);
public void windowClosing(WindowEvent
}
windowEvent)
{
System.exit(0);
} }); 27
WindowAdapter Example – 2 (cont..)
28
WindowAdapter Example – 2 (cont..)
29
Module 7a Example
30
Module 7a Solution
import java.awt.*; f_window.add(p_container);
import java.awt.event.*; f_window.setSize(300, 300);
f_window.setVisible(true);
class GUI7a extends Frame implements ActionListener }
{
Frame f_window; public void actionPerformed(ActionEvent e)
Panel p_container; {
TextField txt1, txt2, txt_res; int num1, num2;
Button btn; try {
num1 = Integer.parseInt(txt1.getText());
GUI7a() { num2 = Integer.parseInt(txt2.getText());
f_window = new Frame("Experiment 7a"); txt_res.setText(num1/num2 + "");
p_container = new Panel(); }
p_container.setLayout(new FlowLayout()); catch(NumberFormatException nfe) {
txt_res.setText("Please do enter only
txt1 = new TextField(20); integers");
txt2 = new TextField(20); }
txt_res = new TextField(20); catch(ArithmeticException ae) {
btn = new Button("Divide"); txt_res.setText("Divisor can not be ZERO");
btn.addActionListener(this); }
p_container.add(txt1); }
p_container.add(txt2); public static void main(String[] args) {
p_container.add(btn); new GUI7a(); }
p_container.add(txt_res); }
31
Module 7a Output
32
Module 8b Example
33
Module 8b Solution
import java.awt.*;
addWindowListener(new WindowAdapter() {
import java.awt.event.*;
public void windowClosing(WindowEvent
public class TrafficLightDemo extends Frame
we)
implements ActionListener
{
{
System.exit(0);
Button redbt,greenbt,yellowbt;
} });
String msg="";
}
TrafficLightDemo()
{
public void actionPerformed(ActionEvent ae)
setLayout(new FlowLayout());
{
redbt=new Button("RED");
msg=ae.getActionCommand();
greenbt=new Button("GREEN");
repaint();
yellowbt=new Button("YELLOW");
}
add(redbt);
public static void main(String args[])
add(greenbt);
{
add(yellowbt);
TrafficLightDemo tf=new TrafficLightDemo();
tf.setTitle("Traffic Light Demo");
redbt.addActionListener(this);
tf.setSize(320,350);
greenbt.addActionListener(this);
tf.setVisible(true);
yellowbt.addActionListener(this);
}
34
Module 8b Solution (Cont..)
public void paint(Graphics g)
{
setBackground(Color.gray);
setForeground(Color.white);
g.setFont(new Font("Arial",Font.BOLD,25));
g.drawOval(110,80,50,50);
g.drawOval(110,180,50,50);
g.drawOval(110,280,50,50);
if(msg.equals("RED")) {
g.setColor(Color.red);
g.fillOval(110,80,50,50);
g.drawString("---->STOP",160,110);
}
else if(msg.equals("GREEN")) {
g.setColor(Color.green);
g.fillOval(110,180,50,50);
g.drawString("---->GO",160,210);
}
else if(msg.equals("YELLOW")) {
g.setColor(Color.yellow);
g.fillOval(110,280,50,50);
g.drawString("---->READY",160,310);
}
} 35
Module 8b Solution (Cont..)
36
THANK YOU
37