UNIT-IV Event Handling
UNIT-IV Event Handling
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical User
Interface (GUI) for java programs.
Why AWT is platform dependent? Java AWT calls native platform (Operating systems) subroutine for
creating components such as textbox, checkbox, button etc. For example an AWT GUI having a button would
have a different look and feel across platforms like windows, Mac OS & Unix, this is because these platforms
have different look and feel for their native buttons and AWT directly calls their native subroutine that creates
the button. In simple, an application build on AWT would look like a windows application when it runs on
Windows, but the same application would look like a Mac application when runs on Mac OS.
AWT components are considered heavy weight because they are being generated by underlying operating
system (OS). For example if you are instantiating a text box in AWT that means you are actually asking OS to
create a text box for you.
Swing is a preferred API for window based applications because of its platform independent and light-weight
nature. Swing is built upon AWT API however it provides a look and feel unrelated to the underlying
platform. It has more powerful and flexible components than AWT. In addition to familiar components such as
buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll
panes, trees, tables, and lists. We will discuss Swing in detail in a separate tutorial.
AWT hierarchy
All the elements like buttons, text fields, scrollbars etc are known as components. In AWT we have classes for
each component as shown in the above diagram. To have everything placed on a screen to a particular position,
we have to add them to a container. A container is like a screen wherein we are placing components like
buttons, text fields, checkbox etc. In short a container contains and controls the layout of components. A
container itself is a component (shown in the above hierarchy diagram) thus we can add a container inside
container.
Types of containers: As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window, Frame, Dialog and Panel.
As shown in the hierarchy diagram above, Frame and Dialog are subclasses of Window class.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
Let's see a simple example of AWT where we are inheriting Frame class.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
java.awt.Label
A java.awt.Label provides a descriptive text string. Take note that System.out.println() prints
to the system console, NOT to the graphics screen. You could use a Label to label another
component (such as text field) to provide a text description.
Constructors
// Construct a Label with the given text String, of the text alignment
Public Methods
// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT, Label.CENTER
Constructors
public Button(String btnLabel);
// Construct a Button with the given label
public Button();
// Construct a Button with empty label
Public Methods
public String getLabel();
// Get the label of this Button instance
public void setLabel(String btnLabel);
// Set the label of this Button instance
public void setEnable(boolean enable);
// Enable or disable this Button. Disabled Button cannot be clicked.
The getLabel() and setLabel() methods can be used to read the current label and modify the
label of a button, respectively.
Clicking a button fires a so-called ActionEvent and triggers a certain programmed action
Constructors
Public Methods
Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".
To find out the state of a checkbox object we can use getState() that returns a true
or false value.
We can also get the label of the checkbox using getLabel() that returns a String
object.
Constructors are
Checkbox()
Creates a check box with an empty string for its label.
Checkbox(String label)
Creates a check box with the specified label.
Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
CheckboxGroup
CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box
button in "off" state.
Constructor
CheckboxGroup()
Creates a new instance of CheckboxGroup.
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
List (java.awt.List)
List components objects are useful for holding a large number of data items. They
are quite similar to the Choice component, however they can allow for the multiple
selection of items. The list automatically adds a scrollbar if it is required. The list
constructor takes two arguments, the int number of items to be displayed and a
boolean to allow/disallow multiple item selection.
Figure 9.13. A List Component
Choice
Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
Constructor
Choice() :Creates a new choice menu.
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Managing Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may
be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end
has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the
arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the
slider box (or thumb) for the scroll bar
Scrollbar defines the following constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
The first form creates a vertical scroll bar. The second and third forms allow you to specify the orientation of
the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is
Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of the constructor, the initial value of
the scroll bar is passed in initialValue
import java.awt.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new ScrollbarExample();
}
}
Using a TextArea
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea. Following are the constructors for TextArea: TextArea( )
throws HeadlessException TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException TextArea(String str, int numLines, int numChars) throws
HeadlessException TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException
import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must
belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the
MenuItem class.
• The direction of the layout is governed by the container’s component orientation property, which, by
default, is left to right, top to bottom.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
BorderLayout
• The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-
width components at the edges and one large area in the center. The four sides are referred to as north, south,
east, and west. The middle area is called the center.
• Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout.
The second allows you to specify the horizontal and vertical space left between components in horz
and vert, respectively.
• BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
• When adding components, you will use these constants with the following form of add( ), which is defined by
Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will be added
import java.awt.*;
{
BorderLayoutExample()
setLayout(new BorderLayout());
add(new Button("NORTH"),BorderLayout.NORTH);
add(new Button("SOUTH"),BorderLayout.SOUTH);
add(new Button("EAST"),BorderLayout.EAST);
add(new Button("WEST"),BorderLayout.WEST);
add(new Button("CENTER"),BorderLayout.CENTER);
class BorderLayoutJavaExample
frame.setSize(400,150);
frame.setVisible(true);
}
GridLayout
GridLayout lays out components in a two-dimensional grid.
When you instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout.
The second form creates a grid layout with the specified number of rows and columns.
The third form allows you to specify the horizontal and vertical space left between components in horz
and vert, respectively. Either numRows or numColumns can be zero. Specifying numRows as zero
allows for unlimited-length columns.
import java.awt.*;
GridLayoutExample()
setLayout(new GridLayout(4,3));
add(button[i]);
class GridLayoutJavaExample
frame.setSize(400,150);
frame.setVisible(true);
}
CardLayout
The CardLayout class is unique among the other layout managers in that it stores several different
layouts.
Each layout can be thought of as being on a separate index card in a deck that can be shuffled so
that any card is on top at a given time.
This can be useful for user interfaces with optional components that can be dynamically enabled
and disabled upon user input. You can prepare the other layouts and have them hidden, ready to be
activated when needed.
CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout.
The second form allows you to specify the horizontal and vertical space left between components
in horz and vert, respectively
void add(Component panelObj, Object name)
import java.awt.*;
import java.awt.event.*;
CardLayoutExample()
setLayout(card);
add(Btnfirst,"Card1");
add(BtnSecond,"Card2");
add(BtnThird,"Card3");
Btnfirst.addActionListener(this);
BtnSecond.addActionListener (this);
BtnThird.addActionListener(this);
}
card.next(this);
class CardLayoutJavaExample
frame.setSize(220,150);
frame.setResizable(false);
frame.setVisible(true);
}
GridBagLayout
What makes the grid bag useful is that you can specify the relative placement of components by specifying
their positions within cells inside a grid. The key to the grid bag is that each component can be a different size,
and each row in the grid can have a different number of columns. This is why the layout is called a grid bag.
It’s a collection of small grids joined together.
GridBagLayout defines only one constructor, which is shown here:
GridBagLayout( )
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 softwar
The modern approach to handling events is based on the delegation event model. The delegation event model
defines standard and consistent mechanisms to generate and process events. Its concept is quite simple:
a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until
it receives an event. Once received, the listener processes the event and then returns. The advantage of this
design is that the logic that processes events is cleanly separated from the user interface logic that generates
those events.
An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted by the event
source by invoking an agreed method on all event listeners. The event object is passed as argument to the
agreed-upon method. Later the event listeners respond as they fit, like submit a form, displaying a message /
alert etc.
The event handling Java involves four types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
4. Event Adapters
1. Event Sources
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.
2. Event classes
Almost every event source generates an event and is named by some Java class. For example,
the event generated by button is known as ActionEvent and that of Checkbox is known as
ItemEvent. All the events are listed in java.awt.event package.
3. Event Listeners
The events generated by the GUI components are handled by a special group of interfaces
known as "listeners". Note, Listener is an interface. Every component has its own listener,
say, AdjustmentListener handles the events of scrollbar Some listeners handle the events of
multiple components. For example, ActionListener handles the events of Button, TextField,
List and Menus. Listeners are from java.awt.event package.
4. Event Adapters
When a listener includes many abstract methods to override, the coding becomes heavy to the
programmer. For example, to close the frame, you override seven abstract methods of
WindowListener, in which, infact you are using only one method. To avoid this heavy
coding, the designers come with another group of classes known as "adapters". Adapters are
abstract classes defined in java.awt.event package. Every listener that has more than one
abstract method has got a corresponding adapter class
Event Listener Interfaces
• java.awt.Event package : Listener interfaces to handle events.
import java.awt.event.*;
Step 2: Implement the appropriate listener interfaces.
public class sample extends Applet implements listenerinterface1{
Step 3: Register the listener object with the appropriate event source.
event_source_object.addevent_listenername(event_listener_object);
The following program changes the applet background color, whenever the
mouse event occurs.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEvent1 extends Applet implements MouseListener{
public void init() {
this.addMouseListener(this);
}public void mouseClicked(MouseEvent e){
setBackground(Color.blue);
}
public void mouseEntered(MouseEvent e){
setBackground(Color.cyan);}
public void mouseExited(MouseEvent e){
setBackground(Color.green);
}
public void mousePressed(MouseEvent e){
setBackground(Color.magenta);
}
public void mouseReleased(MouseEvent e){
setBackground(Color.yellow);
}
import java.awt.*;
import java.awt.event.*;
class keydemo extends Frame implements KeyListener
{
keydemo()
{
addKeyListener(this);
setTitle("Keyeventdemo");
setLayout(null);
setVisible(true);
setSize(400,400);
}
public void keyReleased(KeyEvent ke)
{
setBackground(Color.orange);
}
public void keyPressed(KeyEvent ke)
{
setBackground(Color.cyan);
}
public void keyTyped(KeyEvent ke)
{
setBackground(Color.magenta);
}
public static void main(String[] args)
{
new keydemo();
}
}
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
component.addActionListener(instanceOfListenerclass);
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter
classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
The default layout manager for a panel is the FlowLayout layout manager.
Constructor:
Panel ()
Creates a new panel using the default layout manager.
Panel(LayoutManager)
Creates a new panel with the specified layout manager.