Delegation event model
• defines standard and consistent mechanisms to generate and process events.
Principle:
• A source generates an event and sends it to one or more listeners.
• The listener waits until it receives an event.
• Once an event is received, the listener processes the event and then returns.
Advantage:
• The application logic that processes events is cleanly separated from the user interface logic that
generates those events.
• A user interface element is able to “delegate” the processing of an event to a separate piece of
code.
• In the delegation event model, listeners must register with a source in order to receive an event
notification.
• This provides an important benefit: notifications are sent only to listeners that want to receive
them.
ActionEvent is generated, whenever an action is performed by the user.
Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field or the item
of a list is double clicked.
ItemEvent is generated when an item is selected or deselected. Following components generate
ItemEvents.
CheckBox : When the state of the CheckBox or radio button is changed.
Radio Button(designed using checkbox and group)
Choice : When the state of a ChoiceBox is changed.
List : When an item in list is selected or deselected.
KeyEvent and MouseEvent Both these events are generated by objects of type Component class and its
subclasses.
The KeyEvent is generated when the user presses or releases a key on the keyboard.
The MouseEvent is generated when the user presses the mouse or moves the mouse.
Ex1:
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b); add(tf);
setSize(300,300);
setLayout(null); setVisible(true);
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
public static void main(String args[]){
new AEvent();
Ex2:
import java.awt.*;
import java.awt.event.*;
public class ButtonClick extends Frame implements ActionListener {
TextField t;
Button bLower,bUpper;
String lowerText="lower case";
public ButtonClick(){
t=new TextField(20);
bLower=new Button(lowerText);
bLower.addActionListener(this);
add(t);
add(bLower);
setVisible(true);
setLayout(new FlowLayout());
setSize(200,200);
}
public void actionPerformed(ActionEvent e) {
String tmp=t.getText();
String s=tmp.toLowerCase();
t.setText(s);
public static void main(String argv[]){
new ButtonClick();
} }
Ex3:
import java.awt.* ;
import java.awt.event.*;
class A extends Frame
implements ActionListener {
TextField t1;
Button b1;
Button b2;
A(){
setLayout(null);
setVisible(true);
t1=new TextField();
t1.setBounds(75,50,100,50);
b1=new Button("To lower");
b1.setBounds(50,200,50,50);
//b1.setSize(10);
b2=new Button("To upper");
b2.setBounds(100,200,50,50);
//b2.setSize(10);
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
add(t1);
public void actionPerformed(ActionEvent obj)
{ String tmp;
if(obj.getSource()==b1)
{ tmp=t1.getText();
String t=tmp.toLowerCase() ;
t1.setText(t); }
if(obj.getSource()==b2)
tmp=t1.getText();
String t=tmp.toUpperCase();
t1.setText(t);}
class B
{ public static void main(String args[])
{ A obj=new A();
Ex 4:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Cal extends Frame implements ActionListener{
Font afont = new Font("Times New Roman", Font.BOLD, 20);
Font bfont = new Font("Comic Sans MS", Font.BOLD, 15);
Font cfont = new Font("Sergoe", Font.PLAIN, 12);
Label l0;
Label l1;
Label l2;
Label l3;
TextField t1;
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("ADD");
Button b2=new Button("SUB");
Button b3=new Button("MUL");
Button b4=new Button("DIV");
Button b5=new Button("Cancel");
Cal(){
l0=new Label("BASIC CALCULATOR APP");
l1=new Label("First Number");
l2=new Label("Second Number");
l3=new Label("Result");
t1=new TextField();
setBackground(Color.BLACK);
l0.setBounds(110, 60, 200, 20); l0.setFont(afont);
l0.setForeground(Color.GREEN);
l1.setBounds(50,100,100,20);
l1.setFont(cfont);
l1.setForeground(Color.blue);
l2.setBounds(50,140,100,20);
l2.setFont(cfont);
l2.setForeground(Color.blue);
l3.setBounds(50,180,100,20);
l3.setFont(cfont);
l3.setForeground(Color.blue);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b1.setFont(bfont);
b1.setBackground(Color.GREEN);
b2.setBounds(110,250,50,20);
b2.setFont(bfont);
b2.setBackground(Color.GREEN);
b3.setBounds(170,250,50,20);
b3.setFont(bfont); b3.setBackground(Color.GREEN);
b4.setBounds(230,250,50,20);
b4.setFont(bfont);
b4.setBackground(Color.GREEN);
b5.setBounds(290,250,50,20); b5.setFont(bfont);
b5.setBackground(Color.GREEN);
add(l0);
add(l1);
add(l2);
add(l3);
add(t1);
add(t2);
add(t3);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
setLayout(null);
setVisible(true);
setSize(400,350);
public void actionPerformed(ActionEvent e){
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(e.getSource()==b1) {
t3.setText(String.valueOf(n1+n2));}//valueOf convert int to string
if(e.getSource()==b2){
t3.setText(String.valueOf(n1-n2));
if(e.getSource()==b3){
t3.setText(String.valueOf(n1*n2));
if(e.getSource()==b4){
t3.setText(String.valueOf(n1/n2));
if(e.getSource()==b5){
System.exit(0);
}}
public static void main(String args[]){
new Cal(); } }
hw:
try:
Design following Calculator( close to real life application)
Item Event
ItemEvent is generated when an item is selected or deselected.
Following components generate ItemEvents.
1. CheckBox : When the state of the CheckBox or radio button is changed.
2. Radio Button(designed using checkbox and group)
3. Choice : When the state of a ChoiceBox is changed.
4. List : When an item in list is selected or deselected.
5. When checkable menu item is selected or deselected
Ex1:
import java.awt.*;
import java.awt.event.*;
public class Itemlistener1 extends Frame implements ItemListener{
Choice c; Label l;
public Itemlistener1(){
setTitle("Choice with ItemListener Demo");
setSize(400,400);
setLayout(null);
setLocationRelativeTo(null);
setVisible(true);
c=new Choice();
l=new Label();
l.setBounds(200, 100, 200, 80);
c.add("Apple");
c.add("Mango");
c.add("Guava");
c.add("Orange");
c.add("Pineapple");
c.add("Grapes");
c.setBounds(100, 100, 200, 80);
add(c);
add(l);
// Add item listener
c.addItemListener(this); }
public static void main(String args[])
{
new Itemlistener1 ();
}
public void itemStateChanged(ItemEvent ie)
{
l.setText("You selected "+c.getSelectedItem());
}
}
Choice Methods:
String getItem(int index)//obtain item name at given index
int getItemCount()//to obtain number of items in list
String getSelectedItem()//return string containing name of item
int getSelectedIndex()//return index of item
Ex 2: code snippet(complete program)
public void itemStateChanged(ItemEvent ie)
l.setText("You selected "+c.getSelectedItem());
if(ie.getStateChange()==ItemEvent.SELECTED)
l.setForeground(Color.red);
l.setBackground(Color.green);
3. KeyListener Interface
• Key event is generated whenever user presses/releases or types a key at the keyboard.
• Key events are fired by the component with the keyboard focus when the user presses or
releases keyboard keys.
• Notifications are sent about two basic kinds of key events:
– The typing of a Unicode character
– The pressing or releasing of a key on the keyboard
Methods of KeyListener Interface
Method Purpose
keyTyped(KeyEvent) Called just after the user types a Unicode character into the listened-to component.
keyPressed(KeyEvent) Called just after the user presses a key while the listened-to component has the focus.
keyReleased(KeyEvent) Called just after the user releases a key while the listened-to component has the focus.
KeyEvent class
Method Purpose
int getKeyChar() Obtains the Unicode character associated with this event.
int getKeyCode() Obtains the key code associated with this event. The key code identifies the particular key on
the keyboard that the user pressed or released. For example, VK_A specifies the key labeled A,
and VK_ESCAPE specifies the Escape key.
boolean Returns true if the key firing the event is an action key. Examples of action keys include Cut,
isActionKey()
Copy, Paste, Page Up, Caps Lock, the arrow and function keys.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="key1.class" width="200" height="100"></applet>*/
public class key1 extends Applet implements KeyListener{
String msg=" ";
TextField t1;
public void init() {
addKeyListener(this);
setBackground(Color.red);
t1 = new TextField(10);
t1.addKeyListener(this);
add(t1);
public void keyPressed(KeyEvent k){
showStatus("KeyPressed");
setBackground(Color.orange);
public void keyReleased(KeyEvent k){
showStatus("KeyRealesed");
setBackground(Color.green);
public void keyTyped(KeyEvent k)
{ }}
4. MouseListener Interface
• Mouse events notify when the user uses the mouse (or similar input device) to interact with a
component.
• Mouse events occur when the cursor enters or exits a component's onscreen area and when the
user presses or releases one of the mouse buttons.
Methods of MouseListener Interface
Method Purpose
mouseClicked(MouseEvent) Called just after the user clicks the listened-to component.
mouseEntered(MouseEvent) Called just after the cursor enters the bounds of the listened-to component.
mouseExited(MouseEvent) Called just after the cursor exits the bounds of the listened-to component.
mousePressed(MouseEvent) Called just after the user presses a mouse button while the cursor is over the listened-to component.
mouseReleased(MouseEvent) Called just after the user releases a mouse button after a mouse press over the listened-to component.
5. MouseMotionListener Interface
• Mouse-motion events notify when the user uses the mouse to move the onscreen cursor.
Methods of MouseMotionListener Interface
Method Purpose
mouseDragged(MouseEvent) Called in response to the user moving the mouse while holding a mouse button down.
This event is fired by the component that fired the most recent mouse-pressed event, even if the
cursor is no longer over that component.
mouseMoved(MouseEvent) Called in response to the user moving the mouse with no mouse buttons pressed. This event is
fired by the component that's currently under the cursor.
MouseEvent class
Method Purpose
int getClickCount() Returns the number of quick, consecutive clicks the user has made (including this event).
For example, returns 2 for a double click.
int getButton() Returns which mouse button, if any, has a changed state. One of the following constants is
returned: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3.
int getX() Return the (x,y) position at which event occurred, relative to the component that fired event.
int getY()
Mouse Entered
Mouse is
moving(397,65)
Mouse is
moving(372,36)
Mouse Exited
Mouse Entered
Mouse Pressed
Mouse is
dragging(492,368)
Mouse is
dragging(493,369)
import java.awt.*;
Mouse is
import java.awt.event.*;
dragging(493,370)
Mouse Released
class MyMouse implements MouseListener,MouseMotionListener {
Mouse is clicked
Frame fr;
Mouse is
Button btn;
moving(511,399)
Label lbl;
Mouse is
TextField tf;
moving(545,421)
public TestMouseAndMouseMotionListener(){
fr = new Frame();
fr.setLayout(null);
fr.setSize(500,300);
fr.setVisible(true);
fr.setBackground(Color.RED);
lbl = new Label("This is a for testing for Mouse Events");
lbl.setSize(300,20);
lbl.setLocation(50,50);
fr.add(lbl);
MyMouse mm=new MyMouse();
fr.addMouseListener(mm);
fr.addMouseMotionListener(mm);
public static void main(String args[]){
new TestMouseAndMouseMotionListener();}
public void mouseEntered(MouseEvent m) {
fr.setBackground(Color.yellow);
System.out.println("Mouse Entered");
public void mouseExited(MouseEvent m) {
fr.setBackground(Color.black);
System.out.println("Mouse Exited");
public void mousePressed(MouseEvent m) {
fr.setBackground(Color.pink);
System.out.println("Mouse Pressed");
public void mouseReleased(MouseEvent m) {
fr.setBackground(Color.blue);
System.out.println("Mouse Released");
public void mouseClicked(MouseEvent m){
fr.setBackground(Color.gray);
System.out.println("Mouse is clicked");
}
public void mouseMoved(MouseEvent m) {
System.out.println("Mouse is moving"+"("+m.getX()+","+m.getY()+")");
CardLayout manages 2 or more components that share same
display space(in such a manner that only one component(card) is visible at a time).
Constructors of CardLayout class:
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with given horizontal and vertical gap.
Methods of CardLayout class:
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to previous card of given container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to specified card with the given name.
first() / last()/ next()/ previous(): is used to next/ previous card visible.
show(): is used to make a specified card visible.
void show(Container parent(deck), String Card_name)
// use layout.show(panel, "Text");
Note: show method is valid for any card, not limited to first, last, next and previous card.
Note: Always use next, previous, first, last and show methods with CardLayout obect
public void add(Container parent, String name): Flips to component that was added to this layout with
the specified name
public void add (String CardName, Container card)(can interchange arguments)
//Flips to component that was added to this layout with the specified name
//cards.add(card1, BUTTONPANEL); cards.add(card2, TEXTPANEL);
panel.add("Button", buttonPanel);
panel.add(textBoxPanel, "Text");
Note: Always use it with FinalCardContainerObect
import java.awt.*; import java.applet.Applet; import java.awt.event.*;
/* CardLayout: Pressing one of three buttons will cause a different "card" to be displayed.*/
public class carddemo extends Applet implements ActionListener {
Panel cardPanel; // the container that will hold the various "cards"
Panel firstP, secondP, thirdP; // each of these panels will constitute the "cards"
Panel buttonP; // panel to hold three buttons
Button first, second, third; // the three buttons
CardLayout ourLayout; // the card layout object
public void init(){
//create cardPanel which is the panel that will contain the three "cards"
cardPanel = new Panel();
//create the CardLayout object
ourLayout = new CardLayout();
//set card Panel's layout to be our Card Layout
cardPanel.setLayout (ourLayout);
//create three dummy panels (the "cards") to show
firstP = new Panel();
firstP.setBackground(Color.red);
secondP = new Panel();
secondP.setBackground(Color.blue);
thirdP = new Panel();
thirdP.setBackground(Color.green);
//create three buttons and add ActionListener
first = new Button("First");
first.addActionListener(this);
second = new Button("Second");
second.addActionListener(this);
third = new Button("Third");
third.addActionListener(this);
//create Panel for the buttons and add the buttons to it
buttonP = new Panel();
// Panel's default Layout manager is FlowLayout
buttonP.add(first);
buttonP.add(second);
buttonP.add(third);
//setLayout for applet to be BorderLayout
this.setLayout(new BorderLayout());
//button Panel goes South, card panels go Center
this.add(buttonP, BorderLayout.SOUTH);
this.add(cardPanel, BorderLayout.CENTER);
// add 3 card panels to the card panel container
// method takes 1.) an Object (the card) 2.) an identifying String(card name)
// first one added is the visible one when applet appears
cardPanel.add(firstP, "First"); //red
cardPanel.add(secondP, "Second"); //blue
cardPanel.add(thirdP, "Third"); //green }
/*respond to Button clicks by showing the so named Panel, note use
of CardLayout method show(Container, "identifying string") */
public void actionPerformed(ActionEvent e){
if (e.getSource() == first)
ourLayout.show(cardPanel, "First");
if (e.getSource() == second)
ourLayout.show(cardPanel, "Second");
// ourLayout.previous(cardPanel);
if (e.getSource() == third)
ourLayout.show(cardPanel, "Third");
// ourLayout.next(cardPanel);
} } // end class
/*<applet code="carddemo.class“
height="500" , width="600"> </applet>*/