Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
383 views

Java AWT Event Handling

The document discusses event handling in AWT. It defines events as changes in the state of an object. There are two types of events - foreground events generated from direct user interaction and background events from system interrupts or timeouts. Event handling uses the delegation event model with key participants being the source that generates events and listeners that process events. The document provides an example of using action listeners to handle button clicks in a GUI.

Uploaded by

rutchelinesarita
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
383 views

Java AWT Event Handling

The document discusses event handling in AWT. It defines events as changes in the state of an object. There are two types of events - foreground events generated from direct user interaction and background events from system interrupts or timeouts. Event handling uses the delegation event model with key participants being the source that generates events and listeners that process events. The document provides an example of using action listeners to handle button clicks in a GUI.

Uploaded by

rutchelinesarita
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

AWT 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.

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This
mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the
Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle
the events.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for providing information of
the occurred event to it's handler. Java provide as with classes for source object.
 Listener - It is also known as event handler.Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the
event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this
model ,Listener needs to be registered with the source object so that the listener can receive the event notification.
This is an efficient way of handling the event because the event notifications are sent only to those listener that
want to receive them.

Steps involved in event handling


 The User clicks the button and the event is generated.
 Now the object of concerned event class is created automatically and information about the source and the
event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener interfaces.These Listener interfaces
forecast some public abstract callback methods which must be implemented by the listener class.
 If you do not implement the any if the predefined interfaces then your class can not act as a listener class
for a source object.

Callback Methods
These are the methods that are provided by API provider and are defined by the application programmer and
invoked by the application developer. Here the callback methods represents an event method. In response to an
event java jre will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the the source must register itself to the listener.

Event Handling Example


AwtControlDemo.java

import java.awt.*;

import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

public AwtControlDemo(){

prepareGUI();

public static void main(String[] args){

AwtControlDemo awtControlDemo = new AwtControlDemo();

awtControlDemo.showEventDemo();

private void prepareGUI(){

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showEventDemo(){

headerLabel.setText("Control in action: Button");

Button okButton = new Button("OK");

Button submitButton = new Button("Submit");

Button cancelButton = new Button("Cancel");

okButton.setActionCommand("OK");

submitButton.setActionCommand("Submit");

cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());

submitButton.addActionListener(new ButtonClickListener());

cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton);

controlPanel.add(submitButton);

controlPanel.add(cancelButton);

mainFrame.setVisible(true);

private class ButtonClickListener implements ActionListener{

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if( command.equals( "OK" )) {

statusLabel.setText("Ok Button clicked.");

else if( command.equals( "Submit" ) ) {

statusLabel.setText("Submit Button clicked.");

else {
statusLabel.setText("Cancel Button clicked.");

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output


AWT Event Listeners

The Event listener represent the interfaces responsible to handle events.


Java provides us various Event listener classes but we will discuss those
which are more frequently used. Every method of an event listener method
has a single argument as an object which is subclass of EventObject class.
For example, mouse event listener methods will accept instance of
MouseEvent, where MouseEvent derives from EventObject.

EventListener interface
It is a marker interface which every listener interface has to extend.This
class is defined in java.util package.

Class declaration
Following is the declaration for java.util.EventListener interface:
public interface EventListener

AWT Event Listener Interfaces:


Following is the list of commonly used event listeners.
Sr. No. Control & Description

1 ActionListener

This interface is used for receiving the action events.

2 ComponentListener

This interface is used for receiving the component events.

3 ItemListener

This interface is used for receiving the item events.

4 KeyListener

This interface is used for receiving the key events.

5 MouseListener

This interface is used for receiving the mouse events.

6 TextListener

This interface is used for receiving the text events.


7 WindowListener

This interface is used for receiving the window events.

8 AdjustmentListener

This interface is used for receiving the adjusmtent events.

9 ContainerListener

This interface is used for receiving the container events.

10 MouseMotionListener

This interface is used for receiving the mouse motion events.

11 FocusListener

This interface is used for receiving the focus events.

Listeners Supported by Swing Components

You can tell what kinds of events a component can fire by looking at the kinds of event listeners you can
register on it. For example, the JComboBox class defines these listener registration methods:

 addActionListener
 addItemListener
 addPopupMenuListener

Thus, a combo box supports action, item, and popup menu listeners in addition to the listener methods it
inherits from JComponent.

Listeners supported by Swing components fall into two categories:

 Listeners that All Swing Components Support


 Other Listeners that Swing Components Support

Listeners that All Swing Components Support

Because all Swing components descend from the AWT Component class, you can register the following listeners on any Swing component:

component listener
Listens for changes in the component's size, position, or visibility.
focus listener
Listens for whether the component gained or lost the keyboard focus.
key listener
Listens for key presses; key events are fired only by the component that has the current keyboard focus.
mouse listener
Listens for mouse clicks, mouse presses, mouse releases and mouse movement into or out of the component's drawing area.
mouse-motion listener
Listens for changes in the mouse cursor's position over the component.
mouse-wheel listener
Listens for mouse wheel movement over the component.
Hierarchy Listener
Listens for changes to a component's containment hierarchy of changed events.
Hierarchy Bounds Listener
Listens for changes to a component's containment hierarchy of moved and resized events.
All Swing components descend from the AWT Container class, but many of them are not used as containers. So, technically speaking, any Swing component can
fire container events, which notify listeners that a component has been added to or removed from the container. Realistically speaking, however, only containers (such as
panels and frames) and compound components (such as combo boxes) typically fire container events.

JComponent provides support for three more listener types. You can register an ancestor listener to be notified when a component's containment ancestors are added
to or removed from a container, hidden, made visible, or moved. This listener type is an implementation detail which predated hierarchy listeners.

The other two listener types are part of the Swing components' conformance to the JavaBeans specification. Among other things, this means that Swing components support
bound and constrained properties and notify listeners of changes to the properties. Property change listeners listen for changes to bound properties and are used by several
Swing components, such asformatted text fields, to track changes on a component's bound properties. Also, property change listeners, as well as vetoable change listeners are
used by builder tools to listen for changes on constrained properties. For more information refer to the Properties lesson in the JavaBeans trail.

Other Listeners that Swing Components Support

The following table lists Swing components and the specialized listeners they support, not including listeners supported by all Components, Containers,
orJComponent s. In many cases, the events are fired directly from the component. In other cases, the events are fired from the component's data or selection model.
To find out the details for the particular component and listener you are interested in, go first to the component how-to section, and then if necessary to the listener how-to
section.

This table lists Swing components with their specialized listeners


Documen
t List
Action Caret Change Item Windo Other
Listener, Selectio
Component Listene Listene Listene Listene w Types of
Undoable n
r r r r Listener Listeners
Edit Listener
Listener
button
check box
color chooser
combo box
dialog
editor pane hyperlink
file chooser
formatted text
field
frame
internal
internal frame
frame
list list data
menu menu
menu key
menu item menu drag
mouse
option pane
password
field
popup
popup menu
menu
progress bar
radio button
slider
spinner
tabbed pane
table
model
table
table
column
model
cell editor
text area
text field
hyperlin
text pane
k
toggle button
tree
expansion
tree will
tree expand
tree model
tree
selection
viewport
(used
by scrollpane
)

You might also like