Monday, 31 March 2014

Delegation Event Model



Delegation model concept is Very simple. Listeners Register with the source. Source Generates the event, makes an event object and send it to the listeners. Listeners Process the event object and returns.

Java provides both the ways that a source can add listeners and can remove the listeners also.


import javax.swing.*;
import java.awt.event.*;

public class MouseListenerEx implements MouseListener{
 public void mouseClicked(MouseEvent e) {
        JOptionPane.showMessageDialog(null, "Mouse Clicked");
    }
  
    public void mouseEntered(MouseEvent e) {
        JOptionPane.showMessageDialog(null, "Mouse Entered");
    }
  
  public void mousePressed(MouseEvent e){
  JOptionPane.showMessageDialog(null, "Mouse Pressed");
  }
    
    public void mouseMoved(MouseEvent e){
        JOptionPane.showMessageDialog(null, "Mouse Moved");
    }
  
  public void mouseReleased(MouseEvent e){
  JOptionPane.showMessageDialog(null, "Mouse Moved");
  }
  
 public void mouseExited(MouseEvent e) {
        JOptionPane.showMessageDialog(null, "Mouse Exited");
    }
}


import java.awt.event.*;
import javax.swing.*;

class EventHandlingEx{
 public static void main(String args[]){
  JFrame myFrame = new JFrame("Event Handling Example");
  MouseListenerEx listener1 = new MouseListenerEx();
  
  /* Create a button */
  JButton myButton = new JButton("Click Me");
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  /* Add Button to the frame */
  myFrame.add(myButton);
  
  /* Registers the Listeners */
  myButton.addMouseListener(listener1);
 }
}


As You Observe the program, Mouse events register with myButton.

Source : myButton
Listener : MouseListener

So Whenever any event occurs, then source generates an event object and send it to the registered listeners.


When Mouse Entered, Below Message dialog appears on the screen.

When Mouse Exited, Below Message dialog appears on the screen.
 When Mouse Pressed, Below Message dialog appears on the screen.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment