0% found this document useful (0 votes)
4 views18 pages

Event_Handling

scs

Uploaded by

kirthimadishetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

Event_Handling

scs

Uploaded by

kirthimadishetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Event Handling

Event Handling:Changing the state of an object is known as an event.Event handling is the


process of how events generated in Java GUI application are processed or handled.

Introduction: 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.

Event handling has three main components:

1. Events:An event is a change in state of an object.


2. Event Source: Event source is an object that generates an event.
3. Listeners: A listener is an object that listens to the event.A listener gets notified when an
event occurs.

Event handling process:A source generates an Event and sends 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 handle events:


1. Implement appropriate interface in the class.
2. Register the component with the listener.

Types of Events:

Important Event Classes and Interface:


Event Classes Description Listener Interface
ActionEvent Generated when button is ActionListener
pressed,menu-item is selected, list-item
is double clicked.
MouseEvent Generated when mouse is dragged, MouseListener
moved, clicked, pressed or released and
also when it enters or exit a component.
KeyEvent Generated when input is received from KeyListener
keyboard.
ItemEvent Generated when check-box or list item ItemListener
is clicked.
TextEvent Generated when value of textarea or TextListener
textfield is changed
MouseWheelEvent Generated when mouse wheel is moved MouseWheelListener

WindowEvent Generated when window is WindowListener


activated,deactivated, deiconified,
iconified, opened or closed.
ComponentEvent Generated when component is hidden, ComponentEventListener
moved, resized or set visible.
ContainerEvent Generated when component is added or ContainerListener
removed from container.
AdjustmentEvent Generated when scroll bar is AdjustmentListener
manipulated
FocusEvent Generated when component gains or FocusListener
loses keyboard focus

//Sample program on Event Handling

1. Create the applet with filename as MyApplet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MyApplet extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPresses(KeyEvent k)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent k)
{
msg=msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,40);
}
}
2. Compile the above MyApplet.java applet.
Javac MyApplet.java
3. Create the html file, example “MyApplet.html” and place the applet code in html file.
<html>
<body>
<applet code=”MyApplet.class” width=”300” height=”100”>
</applet>
</body>
</html>
4. Execute the applet using applet viewer tool at command prompt as shown below:
Appletviewer MyApplet.html

Applet Viewer.MyApplet.class _ X

Applet

Life is beautiful

Key Pressed

Click inside the window area and type text. The text is displayed on the window.
AWT

Java AWT(Abstract Window Toolkit) is an API to develop GUI or windows based applications
in java.AWT components are platform-dependent i.e. components designed on one platform may
look different when displayed on another platform.

Introduction:

AWT(Abstract Window Toolkit) contains large number of classes and methods that allows you
to create and manage graphical user interface(GUI) applications, such as windows,buttons,scroll
bars,etc.The AWT was designed to provide a common set of tools for GUI design that could
work on a variety of platforms. The tools provided by the AWT are implemented using each
platform’s native GUI toolkit, hence preserving the look and feel of each platform. This is an
advantage of using AWT. But the disadvantage of such an approach is that GUI designed on one
platform may look different when displayed on another platform.

The java.awt package provides classes for AWT api such as


TextField,Label,TextArea,RadioButton,CheckBox,Choice,List etc.

Java AWT Hierarchy: The hierarchy of Java AWT classes are given below:

Object Button

Label
Componen
Checkbo

Choice

List

Container

Window Panel

Frame Dialog Applet

Component class:
Component class is at the top of AWT hierarchy.Component is an abstract class that
encapsulates all the attributes of visual component.A component object is responsible for
remembering the current foreground and background colors and the currently selected text font.

Container:
The Container is a component in AWT that can contain another component like
buttons,textfields,labels etc.The classes that extends Container class are known as container such
as Frame,Dialog and Panel.

Window:
The window is the containers that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.

Panel:
The panel is the container that doesn’t contain title bar,border or menu bars.It can have
other components like button,textfield etc.

Frame:
Frame is a top-level container which is used to hold components in it.Components such
as a button,checkbox,radio button,menu,list,table etc.In Java,most of the AWT applications are
created using Frame window.

Constructors of Frame:

Constructor Description
public Frame( ) Creates a Frame window with no name.
public Frame(String name) Creates a Frame window with a name.

Frame Methods:

Methods Description
Public void add(Component comp) This method adds the component, comp, to the
container Frame.
Public void setLayout(LayoutManger object) This method sets the layout of the components
in a container, Frame.
Public void remove(Component comp) This method removes a component, comp,
from the container, Frame.
Public void setSize(int widthPixel,int This method sets the size of a Frame in terms
heightPixel) of pixels.

BorderLayout is the default layout manager of Frame:

The default layout of Frame by which it positions the components in it is BorderLayout,


manager. Hence, if we add components to a Frame without calling it’s setLayout( ) method,
these components are automatically added to the center region using BorderLayout manager.
Note: Remember, using the BorderLayout manager, only one component can be placed in a
region, hence if multiple elements are added to a region, only the last element will be visible.
Creating a Frame:

There are two ways to create a Frame.


They are:1. By Instantiating Frame class.
2.By extending Frame class.

 Creating Frame Window by Instantiating Frame class:


import java.awt.*;
class FrameExample
{
Frame frame;
Label label;
Button button;
FrameExample()
{
frame=new Frame(“Frame”);
lable=new Label(“Welcome!”);
button=new Button(“Button1”);

//Setting layout of components in Frame to FlowLayout frame.setLayout(new


FlowLayout( ));

frame.add(label);
frame.add(button);
frame.setSize(250,200);
frame.setVisible(true);
}
public static void main(String args[])
{
new FrameExample();
}
}
Compile the above program
javac FrameExample.java
Run the above program:
Java FrameExample
Output:
Frame __ X

Button1
Welcome
 Creating Frame window by extending Frame class:

In the last programs of Frame,we could not close the Frame window.Here we are going to
see how we can successfully close the Frame window by extending a WindowAdapter class
and overriding its windowClosing ()method.

import java.awt.*;
import java.awt.event.*;

class FrameExample extends WindowAdapter


{
Frame frame;
Button button1;
Button button2;

FrameExample( )
{
frame=new Frame(“Frame”);
button1=new Button(“Button1”);
button2=new Button(“Button2”);

//Setting the layout of Frame to FlowLayout

frame.setLayout(new FlowLayout());

//Adding Label and Button to Frame

frame.add(button1);
frame.add(button2);

frame.addWindowListner(this);

frame.setSize(210,250);
frame.setVisible(true);
}
public static void main(String args[])
{
new FrameExample();
}

public void windowClosing(WindowEvent we)


{
frame.dispose();
}
}
Compile the above program:
javac FrameExample.java
Run the above program
java FrameExample
Output:
Frame - X

Button Button

Important points to remember:


1. While creating a frame(either by instantiating or extending Frame class).
Following two attributes are must for visibility of the frame:
 setSize(int width,int height);
 setVisible(true);
2. When you create other components like Buttons,TextFilelds,etc.Then you need to add it
to the frame by using the method-add(Component’s Object);

Components:
Component class is at the top of AWT hierarchy.Component is an abstract class that
encapsulates all the attributes of visual component.A component object is responsible for
remembering the current foreground and background colors and the currently selected text font.

Useful Methods of Component class:

Method Description
public void add(Component c) Inserts a component on this component
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.

Containers:

The container is a component since it is a subclass of Component class.Container class


can use all the methods of Component class.
Any class subclass of a Container class is known as a container.Only components can be
added to container.Every container comes with a default layout manager that can be changed
explicitly with setLayout( ) method.

Container Hierarchy Panel Applet


Object Component Container Frame
Important methods of the Container class are:
Window
1. add(): This method is overloaded with which a component can be added to the container.File Dialog
Dialog
2. invalidate( ): Used to invalidate the present set up of components in the container.
3. validate( ): Used to revalidate the current set up of components after calling invalidate( ).

The important containers used very often are applets,frames and panels.

Button:
Button class is used to create a push button control,which can generate an ActionEvent
when it is clicked.In order to handle a button click event, ActionListener interface should be
implemented.Button is a component which extends JComponent class and it can be added to the
container like Frame or a component like Panel.

Constructors of Button:

Constructor Description
public Button( ) Creates a button with no text on it.
public Button(String text) Creates a button with a text on it.

Methods of Button class:

Methods Description
public void setText(String text) Sets a String message on the Button
public String getText( ) Gets a String message of Button
public void setLabel( ) Sets a String text on button.
public String getLabel( ) Gets the String text of this button.

Label:
Label class is used to create a label,which can be used to display a text information to the
user or a text before the textfiled or an image.Label is a component which extends JComponent
class and it is added to the container like Frame or a component like Panel.

Constructor of Label:

Constructor Description
Public Label( ) Creates a Label with an empty text.
Public Label(String text) Creates a Label with an specified text.
Public Label(String text,int Creates a label with an specified text and
alignment) alignment.

Label’s alignment could be any of these fields-


 Label.RIGHT-to align a label to the right.
 Label.CENTER-to align a label to the center.
 Label.LEFT-to align a label to the left.
Methods of Label class:

Methods Description
public void setText(String text) Sets a String message on the Label.
public String getText( ) Gets a String message of Label.
void setAlignment(int alignment) Sets an alignment on this label.
void int getAlignment( ) Gets the current alignment of this label.

Checkbox:
Checkbox is another Java component used by the programmer when the user is
left with two options only-either yes or no,that is, want or don’t want.The check box
when selected by the user,returns true and when deselected returns false.The checkbox
toggles between two states-true or false.The state can be obtained with getState( )
method.

The Checkbox generates ItemEvent and is handled by ItemListener.

Constructors of Checkbox:

Constructor Description
Public Checkbox( ) Creates a checkbox with no text,this
checkbox is unchecked by default.
Public Checkbox(String text) Creates a checkbox with a text,this
checkbox is unchecked by default.
Public Checkbox(String text,Boolean b) Creates a checkbox with a text,this
checkbox is checked or unchecked
depending on the boolean value.

Methods of Checkbox class

Methods Description
public void setName(String text) Sets a name on the Checkbox,this name
will not be displayed.
public String getName( ) Gets a String message of Checkbox,this
name will not be displayed.
public void setLabel( ) Sets a String text on button.
public String getLabel( ) Gets the String text of this button
public void setState(boolean b) Sets a state of Checkbox.
P ublic boolean getState( ) Gets the state of Checkbox.

Radio Buttons:
In java.awt we do not have a special class for radio buttons but we can create
radio button from Checkbox class.In java.awt we have a predefined class called
CheckboxGroup.The object of CheckboxGroup class is used to group together a set of
Checkbox.
Container Class:
Container is the super class of all Java containers.
Following is the Container class signature-

public class Container extends Component

Important methods of the Container class are:


 Add( ):This method is overloaded with which a component can be added to the
container.
 Invalidate( ):Used to invalidate the present set up of components in the container.
 Validate( ):Used to revalidate the current set up of components after calling
invalidate( ).
The important container used very often are applets,frames and panels.

Layouts:
The java.awt library provides 5 basic layouts. Each layout has its own significance and all
of them are completely different. The 5 layouts available in the java.awt library are:
1. Border Layout.
2. Grid Layout.
3. GridBag Layout.
4. Card Layout.
5. Card Layout.
6. Flow Layout

 Border Layout: The BorderLayout is a layout which organizes components in terms of


direction.A border layout divides the frame or panel into 5 sections-North,South,East
West and Center.Each component can be arranged in aparticular direction by passing an
additional argument.
BorderLayout - X
North

West center East

South
Border Layout
 Grid Layout:
A GridLayout is a more organized way of arranging components.It divides the frame or
panel in the form of a grid containing evenly distributed cells.Each component get added
to a particular cell.The order of placement of components is directly dependant on the
order in which they are added to the frame or panel.The below image shows a 2 column 3
row GridLayout based Frame.

Grid Layout - X

Button1 Button2

Button3 Button4

Button5 Button6

Grid Layout

 GridBag Layout:

The GridBagLayout is the most flexible layout which provides an organized yet flexible
way to arrange components.It provides developers with the flexibility to choose the exact
location of the component, in a grid, it’s row span and column span as well as the horizontal and
vertical gap.The below image shows a GridBagLayout.It contains Button 5 which spans 2 rows
at a time.

 Card Layout:
This is the layout which is rarely used and is utilized to stack up components one
above another.The CardLayout allows components to stay over one another and
switch any component to the front as per the requirement.

 Flow Layout:
As the name indicates,FlowLayout is the layout which allows components to flow
to and end of the visible part is reached.A FlowLayout basically helps develop
more responsive UI and keep the components in a free flowing manner.The below
image shows an actual flow layout with 6 Components.

You might also like