Java GUI Event Handling:-
Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven. Event describes the change in state of any
object. For Example : Pressing a button, Entering a character in Textbox, Clicking
or Dragging a mouse, etc.
Events : An event is a change in state of an object.
Events Source : Event source is an object that generates an event.
Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.
How Events are handled?
A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and then
return. Events are supported by a number of Java packages, like java.util, java.awt
and java.awt.event.
How Events are handled?
A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and then
return. Events are supported by a number of Java packages, like java.util, java.awt
and java.awt.event.
Steps to perform Event Handling:-
Following steps are required to perform event handling:
Register the component with the Listener:-
Registration Methods
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){}
Program of Event Handling
import java.awt.*;
import java.awt.event.*;
class AwtEvent extends Frame implements ActionListener{
TextField tf;
AwtEvent(){
//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[]){
AwtEvent a= new AwtEvent();
}
}