Module 4 21CS32 Notes
Module 4 21CS32 Notes
Module -5
Event Handling
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling,
etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events
are generated due to interaction by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur.
To handle the events, Java follows the Delegation Event model.
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source with Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Notifications are sent only to listeners that want to receive them which is more efficient way
to handle event.
The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
Accelerates the performance of the application which has multiple events.
1. EVENT SOURCES
A source is an object that generates an event.
Event sources are components, subclasses of java.awt.Component, capable to generate
events. The event source can be a button, TextField or a Frame etc.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
2. EVENT CLASSES
The classes that are responsible for handling events in event handling mechanism are event
classes.
3. EVENT LISTENERS
A listener is an object that is notified when an event occurs.
It has two major requirements.
First, it must have been registered with one or more sources to receive notificationsabout
specific types of events.
Second, it must implement methods to receive and process these notifications
4. EVENT ADAPTERS
Adapters are abstract classes for receiving various events. The methods in these classes
are empty. These classes exists as convenience for creating listener objects.
Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface. You can define a new class to act as an
event listener by extending one of the adapter classes and implementing only those events inwhich
you are interested.
E.g. Suppose you want to use MouseClicked Event or method from MouseListener, if you do not
use adapter class then unnecessarily you have to define all other methods fromMouse, But If you
use adapter class then you can only define MouseClicked method and don ’t worry about other
method definition because class provides an empty implementation of allmethods in an event
ActionEvent Class
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
ActionEvent has these three constructors:
String getActionCommand( )
The getModifiers( ) method returns a value that indicates which modifier keys (ALT,
CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown
here:
int getModifiers( )
The method getWhen( ) returns the time at which the event took place. This is called the
event’s timestamp. The getWhen( ) method is shown here:
long getWhen( )
AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment
events.
AdjustmentEvent constructor:
Here, src is a reference to the object that generated this event. The id specifies the event. The type
of the adjustment is specified by type, and its associated data is data.
ContainerEvent Class
A ContainerEvent is generated when a component is added to or removed from a
container.
There are two types of container events. The ContainerEvent class defines int constants that
can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.
ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)
Here, src is a reference to the container that generated this event. The type of the event is specified
by type, and the component that has been added to or removed from the container is comp.
FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events are
identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag,
Component other)
Here, src is a reference to the component that generated this event. The type of the event is
specified by type. The argument temporaryFlag is set to true if the focus event is temporary.
Otherwise, it is set to false.
You can determine the other component by calling getOppositeComponent( ), shown here:
Component getOppositeComponent( ) The opposite component is returned.
InputEvent Class
It is the superclass for component input events.
Its subclasses are KeyEvent and MouseEvent.
InputEvent defines several integer constants that represent any modifiers, such as the control
key being pressed, that might be associated with the event.
To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods.
The forms of these methods are shown here:
boolean isAltDown( )
ItemEvent Class
An ItemEvent is generated when a check box or a list item is clicked or when a checkable
menu item is selected or deselected.
There are two types of item events, which are identified by the following integer constants:
KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and
KEY_TYPED.
MouseWheelEvent Class
The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of
MouseEvent.
MouseWheelEvent defines these two integer constants:
TextEvent Class
These are generated by text fields and text areas when characters are entered by a user or
program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type.
WindowEvent Class
There are ten types of window events.
getWindow( ). It returns the Window object that generated the event. Its general form is
shown here:
Window getWindow( )
Sources of Events
ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:
This interface defines four methods that are invoked when a component is resized, moved, shown,
or hidden.
Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ContainerListener Interface
This interface contains two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a container,
componentRemoved( ) is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus, focusGained( )
is invoked. When a component loses keyboard focus, focusLost( ) is called.
Their general forms are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
The ItemListener Interface
import java.awt.*;
import java.awt.event.*;
class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
}
public class keyboard{
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface. Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you
were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and override mouseDragged( ). The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Inner Classes
An inner class is a class defined within another class, or even within an expression.
import java.applet.*;
import java.awt.event.*;
Swings
Swing contains a set of classes that provides more powerful and flexible GUI components than
those of AWT. Swing provides the look and feel of modern Java GUI. Swing library is an official
Java GUI tool kit released by Sun Microsystems. It is used to create graphical user interface with
Java.
Swing is a set of program component s for Java programmers that provide the ability to create
graphical user interface ( GUI ) components, such as buttons and scroll bars, that are independent
of the windowing system for specific operating system.
Model-View-Controller
One component architecture is MVC - Model-View-Controller.
The model corresponds to the state information associated with the component. The view
determines how the component is displayed on the screen. The controller determines how the
component responds to the user. Swing uses a modified version of MVC called "Model-Delegate".
In this model the view (look) and controller (feel) are combined into a "delegate".
Components
Swing components are derived from the JComponent class.
The only exceptions are the four top-level containers:
JFrame, JApplet, JWindow, and JDialog.
JComponent inherits AWT classes Container and Component.
All the Swing components are represented by classes in the javax.swing package.
All the component classes start with J: JLabel, JButton, JScrollbar, ...
Containers
There are two types of containers:
Explanation:
The program begins by importing javax.swing. As mentioned, this package contains the
components and models defined by Swing.
For example, javax.swing defines classes that implement labels, buttons, text controls, and
menus. It will be included in all programs that use Swing. Next,
the program declares the FirstSwing class
It begins by creating a JFrame, using this line of code:
The setSize( ) method (which is inherited by JFrame from the AWT class Component) sets the
dimensions of the window, which are specified in pixels. in this example, the width of the window is
set to 400 and the height is set to 500.
By default, when a top-level window is closed (such as when the user clicks the close box), the window
is removed from the screen, but the application is not terminated.
If want the entire application to terminate when its top-level window is closed. There are a couple of
ways to achieve this. The easiest way is to call setDefaultCloseOperation( ), as the program does:
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Swing Applet
A Swing applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet
includes all of the functionality found in Applet and adds support for Swing. JApplet is a top-level
Swing container, which means that it is not derived from JComponent. Because JApplet is a
toplevel container, it includes the various panes described earlier. This means thatall components
are added to JApplet’s content pane in the same way that components are added to JFrame’s
content pane.
JLabel can be used to display text and/or an icon. It is a passive component in that it does not
respond to user input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str is the string to be initially presented, and cols is the number of columns in the text field.
If no string is specified, the text field is initially empty. If the number of columns is not specified,
the text field is sized to fit the specified string.
JPasswordField is a lightweight component that allows the editing of a single line of text
where the view indicates something was typed, but does not show the original characters.
import javax.swing.*;
public class JTextFieldPgm
{
public static void main(String[] args)
{
JFrame f=new JFrame("My App");
JLabel namelabel= new JLabel("User ID: ");
namelabel.setBounds(10, 20, 70, 10);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 50, 70, 10);
f.add(namelabel);
f.add(passwordLabel);
f.add(userText);
f.add(passwordText);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
The align argument specifies the horizontal alignment of the text and/or icon within the dimensions
of the label. It must be one of the following values: LEFT, RIGHT, CENTER.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and
encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s
constructor.
ImageIcon(String filename)
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
JRadioButton
JCheckBox
A JCheckBox is the Swing equivalent of the Checkbox component in AWT. This is sometimes
called a ticker box, and is used to represent multiple option selections in a form.
JComboBox
The JComboBox class is used to create the combobox (drop-down list). At a time only one item
can be selected from the item list.
JTabbedpane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with
tabs. Selecting a tab causes the component associated with that tab to come to the forefront. Tabbed
panes are very common in the modern GUI.
Given the complex nature of a tabbed pane, they are surprisingly easy to create and use.
JTabbedPane defines three constructors.
We will use its default constructor, which creates an empty control with the tabs positioned across
the top of the pane.
The other two constructors let you specify the location of the tabs, which can be along any of the
four sides. JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling
addTab( ) method. Here is one of its forms:
Here, name is the name for the tab, and comp is the component that should be added to the tab.
Often, the component added to a tab is a JPanel that contains a group of related components. This
technique allows a tab to hold a set of components.
JList
In Swing, the basic list class is called JList.
It supports the selection of one or more items from a list. Although the list often consists of strings,
it is possible to create a list of just about any object that can be displayed.
JList is so widely used in Java that it is highly unlikely that you have not seen one before.
JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines how access to the list
data is achieved.
The second model is the ListSelectionModel interface, which defines methods that determine what
list item or items are selected.
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
******************************End of Module-4********************************