Thursday, 26 March 2015

Event and Listener

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Event classes and Listener interfaces:

Event Classes
Listener Interfaces
ActionEvent
ActionListener
MouseEvent
MouseListener and MouseMotionListener
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:
  1. Implement the Listener interface and overrides its methods
  2. Register the component with the Listener
For registering the component with the Listener, many classes provide the registration methods. For example:
  • Button
    • public void addActionListener(ActionListener a){}
  • MenuItem
    • public void addActionListener(ActionListener a){}
  • TextField
    • public void addActionListener(ActionListener a){}
    • public void addTextListener(TextListener a){}
  • TextArea
    • public void addTextListener(TextListener a){}
  • Checkbox
    • public void addItemListener(ItemListener a){}
  • Choice
    • public void addItemListener(ItemListener a){}
  • List
    • public void addActionListener(ActionListener a){}
    • public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following places:
  1. Same class
  2. Other class
  3. Annonymous class

Example of event handling within class:


  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3.   
  4. class AEvent extends Frame implements ActionListener{  
  5. TextField tf;  
  6. AEvent(){  
  7.   
  8. tf=new TextField();  
  9. tf.setBounds(60,50,170,20);  
  10.   
  11. Button b=new Button("click me");  
  12. b.setBounds(100,120,80,30);  
  13.   
  14. b.addActionListener(this);  
  15.   
  16. add(b);add(tf);  
  17.   
  18. setSize(300,300);  
  19. setLayout(null);  
  20. setVisible(true);  
  21.   
  22. }  
  23.   
  24. public void actionPerformed(ActionEvent e){  
  25. tf.setText("Welcome");  
  26. }  
  27.   
  28. public static void main(String args[]){  
  29. new AEvent();  
  30. }  
  31. }  

No comments:

Post a Comment