Event Handling
Event Handling
What is an Event?
Change in the state of an object is known as event i.e. event
describes the change in state of source. Events are generated as
result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item
from list, scrolling the page are the activities that causes an
event to happen.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the
direct interaction of user.They are generated as
consequences of a person interacting with the graphical
components in Graphical User Interface. For example,
clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list,
scrolling the page etc.
Background Events - Those events that require the
interaction of end user are known as background events.
Operating system interrupts, hardware or software failure,
timer expires, an operation completion are the example of
background events.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide
the registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
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
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.