Advanced Java
Chapter 3
Event Handling & Event Delegation Model
Thought of a Day
                   2
        Delegation Event Model
   Event: Action Preformed or state is changed.eg key is
    pressed, mouse is clicked, Checkbox is selected
   Package: java.awt.event
   Model requires 1.Event, 2. EventSource,
    3.EventListener
   Steps:
       Select the Event
       Implement appropriate Listener
       Register the event with concern source
       Select the method of listener class and write code fr event
                                                                      3
Delegation Event Model-figure
               Event Listener
          output                           object
          Prepared By Dr. S. H. Kulkarni            4
        Events –Source, Class, Listener
Sr. No. Source of Event   Event class   Event Listener   Methods
       Keyboard           FocusEvent     FocusListener    void
1      gains or loses                                    focusGained(FocusEvent fe)
       focus                                             void focusLost(FocusEvent
                                                         fe)
2.     Input is      KeyEvent            KeyListener     void keyPressed(KeyEvent e)
       received from                                     void keyReleased(KeyEvent
       Keyboard                                          e)
                                                         void keyTyped(KeyEvent e)
                                                                                       5
            Events –Source, Class, Listener
Sr. No. Source of Event   Event class     Event Listener     Methods
3       Button, List, Menu ActionEvent    ActionListener     Void actionPerformed(
                                                             ActionEvent ae)
4.      Scrollbar         AdjustmentEvent AdjustmentListener Void adjustmentValueChanged(
                                                             AdjustmentEvent ae)
5.      TextField,TextAre TextEvent       TextListener       Void textChanged(TextEvent te)
        a
                                                                                              6
              Events –Source, Class, Listener
Sr. No.   Source of Event   Event class   Event Listener     Methods
5.        Checkbox,Choi ItemEvent         ItemListener       Void
          ce,Menu                                            itemStateChanged(ItemEvent
          selection                                          ie)
6.        Mouse             MouseEvent    MouseListener       1.void mouseClicked(MouseEvent
                                                              me)
                                                              2.void mouseEntered(MouseEvent
                                                              me)
                                                              3.void mouseExited(MouseEvent
                                                              me)
                                                              4.Void mousePressed(MouseEvent
                                                              me)
                                                              5.void mouseReleased(MouseEvent
                                                              me)
                                          MouseMotionListener 1.void mouseDragged(MouseEvent
                                                              me)
                                                              2.void mouseMoved(MouseEvent
                                                              me)                             7
               Events –Source, Class, Listener
Sr.   Source Event class   Event Listener   Methods
No.   of Event
7.    Window
               WindowEvent WindowListener 1. void windowActivated(WindowEvent 
                                          e);  
                                          2. void windowClosed(WindowEvent e);
                                            
                                          3. void windowClosing(WindowEvent e)
                                          ;  
                                          4. void windowDeactivated(WindowEve
                                          nt e);  
                                          5. void windowDeiconified(WindowEve
                                          nt e);  
                                          6.void windowIconified(WindowEvent e
                                          );  
                                          7. void windowOpened(WindowEvent e)
                                          ;  
                                                                                 8
    Button as a source of event
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
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();
}
}
                                                        9
Output
         10
Thought of a Day
                   11
Button as a Source of Event
                              12
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
  int n1=Integer.parseInt(t1.getText());
 int n2=Integer.parseInt(t2.getText());
int sum=n1+n2;
t3.setText(Integer.toString(sum));
}
}
                                              13
Thought of a Day
                   14
Checkbox as a source of Event
                                15
       Algorithm
1.   Source-Checkbox
2.   Event Class-?
3.   Event Listener-?
4.   Create a public class & implement Event Listener
5.   Design GUI using applet
6.   Register an Event
7.   Call methods of Listener class
                                                        16
Thought of a Day
                   17
       Algorithm
1.   Source-Mouse
2.   Event Class-?
3.   Event Listener-?
4.   Create a public class & implement Event Listener
5.   Register an Event
6.   Call methods of Listener class
                                                        18
     Mouse as a source of Event
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*<applet code="MouseListenerDemo.class" height=300 width=200>
</applet>*/
public class MouseListenerDemo extends Applet implements
MouseListener, MouseMotionListener
//implements the listeners
   {
    String msg="";
    int mousex=0,mousey=0;
    public void init()
       {
       addMouseListener(this); //register the event
       addMouseMotionListener(this);
       }
                                                                 19
// Calling listener methods
   public void mouseClicked(MouseEvent e)
   {
     mousex=0;
          mousey=10;
     msg="Mouse Clicked";
          repaint();
   }
   public void mouseEntered(MouseEvent e)
          {
     mousex=0;
          mousey=10;
     msg="Mouse Entered";
          repaint();
          }
                                            20
public void mouseExited(MouseEvent e)
       {
       mousex=0;
       mousey=10;
    msg="Mouse Exited";
       repaint();
       }
 public void mousePressed(MouseEvent e)
       {
       mousex=e.getX();
       mousey=e.getY();
    msg="Mouse Down";
       repaint();
    }
                                          21
public void mouseReleased(MouseEvent e)
         {
          mousex=e.getX();
        mousey=e.getY();
    msg="Mouse up";
    showStatus("Dragging Mouse at" +mousex+","+mousey);
        repaint();
        }
 public void mouseDragged(MouseEvent e)
        {
     mousex=e.getX();
        mousey=e.getY();
    msg="*";
    showStatus("Dragging Mouse at" +mousex+","+mousey);
        repaint();
        }
                                                          22
public void mouseMoved(MouseEvent e)
        {
     showStatus("Moving Mouse at"
+mousex+","+mousey);
        repaint();
        }
  public void paint(Graphics g)
     {
      g.drawString(msg,mousex,mousey);
    }
}
                                         23
Output of a Program
                      24
25
         KeyEvent Class
 A KeyEvent is generated when keyboard input occurs.
•         There are three types of key events, which are identified by
these integer constants:
         KEY_PRESSED,
         KEY_RELEASED, and
         KEY_TYPED.
•       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 the SHIFT key does not generate a
character.
                                                                    26
         Key Event Constants
•       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. Here are
some others:
VK_ENTER VK_ESCAPE VK_CANCELVK_UP
VK_DOWN VK_LEFT              VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP           VK_SHIFT VK_ALT                  VK_CONTROL
Virtual key code
•        The VK constants specify virtual key codes and are
independent of any modifiers, such as control, shift, or alt.
                                                                        27
        Constructor of KeyEvent
KeyEvent is a subclass of InputEvent. Here are two of its
constructors:
KeyEvent(Component src, int type, long when, int modifiers, int
code)
KeyEvent(Component src, int type, long when, int modifiers, int
code, char ch)
                Here, src is a reference to the component that generated
the event.
The type of the event is specified by type. The system time at which
the key was pressed is passed in when. The modifiers argument
indicates which modifiers were pressed when this key event occurred.
The virtual key code, such as VK_UP, VK_A, and so forth, is passed
                                                                           28
       Methods of KeyEvent class
   The KeyEvent class defines several methods, but the
most commonly used ones are
1) getKeyChar( ), which returns the character that was
entered.
    syntax:
    char getKeyChar( )
     If no valid character is available, then getKeyChar( )
returns CHAR_UNDEFINED.
2) getKeyCode( ), which returns the key code
    Syntax:.
    int getKeyCode( )
                                                              29
       The KeyListener Interface
 This interface defines three methods.
 The keyPressed( ) and keyReleased( ) methods are invoked when a
key is pressed and released, respectively.
   The keyTyped( ) method is invoked when a character has been
entered.
For example, if a user presses and releases the A key, three events are
generated in sequence: key pressed, typed, and released. If a user
presses and releases the HOMEkey, two key events are generated in
sequence: key pressed and released.
 The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
                                                                          30
      Stepwise Procedure :
   Import all required packages
   Implements KeyListener interface.
   Use various methods of key event
    class.
   Assign the event control.
   Execute the program and see the
    various key activity in applet window.
                                             31
             Program
java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="SimpleKey1" width=300 height=100>
</applet>
*/
public class SimpleKey1 extends JApplet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}                                                 32
        Window as a source of event
1.public abstract void windowActivated(WindowEvent e);  
2.public abstract void windowClosed(WindowEvent e);  
3.public abstract void windowClosing(WindowEvent e);  
4.public abstract void windowDeactivated(WindowEvent e);  
5.public abstract void windowDeiconified(WindowEvent e);  
6.public abstract void windowIconified(WindowEvent e);  
7.public abstract void windowOpened(WindowEvent e);  
                                                             33
import java.awt.*;  
import java.awt.event.WindowEvent;  
import java.awt.event.WindowListener;  
public class WindowExample extends Frame implements Windo
wListener{  
    WindowExample(){  
        addWindowListener(this);  
          
        setSize(400,400);  
        setLayout(null);  
        setVisible(true);  
    }  
      
                                                            34
public static void main(String[] args) {  
    new WindowExample();  
}  
public void windowActivated(WindowEvent arg0) {
  
    System.out.println("activated");  
}  
public void windowClosed(WindowEvent arg0) {  
    System.out.println("closed");  
}  
                                                  35
What is next?
                36
           JPasswordField
- allows editing of a single line of text
- does not show the actual characters.* is displayed
- JPasswordField inherits the JTextField class of javax.swing
  package.
Constructors of the class are :
1. JPasswordField(): Default constructor that creates a new PasswordField
2. JPasswordField(int columns) : constructor that creates a new empty
   PasswordField with specified number of columns.
3. JPasswordField(String Password) : constructor that creates a new
   empty Password field initialized with the given string.
4. JPasswordField(String Password, int columns) : constructor that
   creates a new empty PasswordField with the given string and a specified
   number of columns .
5. JPasswordField(Document doc, String Password, int columns) 
                                                                             37
     Commonly used method of JPasswordField
1.char getEchoChar() : returns the character used for
echoing in JPasswordField.
2.setEchoChar(char c) : set the echo character for
JPasswordField.
3.String getPassword() : returns the text contained in
JPasswordField.
4.String getText() : returns the text contained in
JPasswordField.
                                                         38
     Program to create Login Page
Algorithm
1.Source of event
2.Event class
3.Event Listener
4.Create public class & implement Listener
5.Design GUI
6.Register the event
7.Call listener method
8.Read values of text field & display it
                                             39
Thought of a Day
                   40
     Java Adapter Classes
 Drawback of Delegation Event Model
-Writing of every method of Listener is compulsory
-Example- MouseListener has 5 methods mouseClicked(),
mousePressed(),
mouseEntered(),mouseReleased(),mouseExited()
-We may need only one method then also we have to
write all other 4 methods
-Java adapter classes provide the default implementation
of listener interfaces.
-If you inherit the adapter class, you will not be forced to
provide the implementation of all the methods of listener
interfaces.
-So it saves code.
-The adapter classes are found in java.awt.event
                                                               41
       Adapter classes
Adapter class        Listener interface
WindowAdapter        WindowListener
KeyAdapter           KeyListener
MouseAdapter         MouseListener
MouseMotionAdapter   MouseMotionListener
FocusAdapter         FocusListener
ComponentAdapter     ComponentListener
ContainerAdapter     ContainerListener
                                           42
     Mouse as a source with Adapter Classes
Algorithm:
1.Select the source of event
2.Find event Adapter class , Listener and its method
3.Create Frame & extend from Adapter class
4.Design GUI if needed
5.Register the event using addXXX()
6.Write code inside selected method as per problem
statement
7.Use main() to execute the Frame
                                                       43
          Mouse as a source with Adapter Classes
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
  JFrame f;
  MouseAdapterExample(){
     f=new JFrame("Mouse Adapter");
     f.addMouseListener(this);
       f.setSize(300,300);
     f.setLayout(null);
     f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
  public void mouseClicked(MouseEvent e) {
    Graphics g=f.getGraphics();
    g.setColor(Color.BLUE);
    g.fillOval(e.getX(),e.getY(),30,30);
  }
   public static void main(String[] args) {
  new MouseAdapterExample(); } }
                                                          44
Output
         45
     Key as a source with Adapter Classes
Algorithm:
1.Select the source of event
2.Find event Adapter class , Listener and its method
3.Create Frame & Implement the Listener
4.Design GUI if needed
5.Register the event using addXXX()
6.Write code inside selected method as per problem
statement
7.Use main() to execute the Frame
                                                       46
              Key as a source of event using Adapter class
import java.awt.*;
import java.awt.event.*; import javax.swing.*;
public class KeyAdapterExample extends KeyAdapter{
   JLabel l;
  JTextArea area;
   JFrame f;
   KeyAdapterExample(){
      f=new JFrame("Key Adapter");
      l=new JLabel();
      l.setBounds(20,50,200,20);
      area=new JTextArea();
      area.setBounds(20,80,300, 300);
      area.addKeyListener(this);
       f.add(l);f.add(area);
      f.setSize(400,400);
      f.setLayout(null);
      f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void keyReleased(KeyEvent e) {
      String text=area.getText();
      String words[]=text.split("\\s");
      l.setText("Words: "+words.length+" Characters:"+text.length());
   }
     public static void main(String[] args) {
      new KeyAdapterExample(); } }
                                                                              47
Thought of a Day
      Java inner class
Inner class is a class which is declared inside the
class or interface.
We use inner classes to logically group classes and
interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer
class including private data members and methods.
Syntax
class Java_Outer_class
{  
 //code  
 class Java_Inner_class{  
  //code  
 }  
}  
                                                          49
        Types of Inner classes
   1.Member inner class
   2.Anonymous inner class
   3.Local inner class
Type                         Description
Member Inner Class           A class created within class and
                             outside method.
Anonymous Inner Class        A class created for
                             implementing interface or
                             extending class. Its name is
                             decided by the java compiler.
Local Inner Class            A class created within method.
                                                                50
                Java Member inner class
A non-static class that is created inside a class but outside a method is
called member inner class.
Syntax:
class Outer{
 //code
 class Inner{
  //code
 }
}
                                                                            51
         Example of Member Inner class
class TestMemberOuter1{ //outer class
 private int data=30;
 class Inner{ //inner class
  void msg(){System.out.println("data is "+data);}
 }
 public static void main(String args[]){
  TestMemberOuter1 obj=new TestMemberOuter1(); //obj outer
  TestMemberOuter1.Inner in=obj.new Inner(); //obj inner
  in.msg();
 }
}
Output=30
                                                             52
       Anonymous Inner class
•   A class that have no name is known as
    anonymous inner class in java.
•   It should be used if you have to override
    method of class or interface.
                                                53
      Anonyms Inner Classes
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());//Anonyms Inner class
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
                                                           54
   Java Local inner class
•A class i.e. created inside a method
is called local inner class in java.
•If you want to invoke the methods
of local inner class, you must declare
this class inside the method.
                                         55
       Java local inner class example
public class localInner1{  
 private int data=30;//instance variable  
 void display()
{  
  class Local{ //class declared inside method
   void msg(){System.out.println(data);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner1 obj=new localInner1();  
  obj.display();  
 }  }  
Output=30                                       56
57
Thought of a day
Thought of a Day
                   59