0% found this document useful (0 votes)
9 views21 pages

Understanding Event Handling in Java

Uploaded by

Akshatha
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)
9 views21 pages

Understanding Event Handling in Java

Uploaded by

Akshatha
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

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.
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 its 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 processes 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 listeners 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.
AWT Event Classes:
 Following is the list of commonly used event classes.
Sr. Control & Description
No.
1 AWTEvent
It is the root event class for all AWT events. This class and its subclasses
supercede the original [Link] class.
2 ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double
clicked.
3 InputEvent
The InputEvent class is root event class for all component-level input events.
4 KeyEvent
On entering the character the Key event is generated.
5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.
9 ComponentEvent
The object of this class represents the change in state of a window.
10 ContainerEvent
The object of this class represents the change in state of a window.
11 MouseMotionEvent
The object of this class represents the change in state of a window.
12 PaintEvent
The object of this class represents the change in state of a window.

KeyEvent
On entering the character, the Key event is generated. There are three types of key events
which are represented by the integer constants. These key events are following
 KEY_PRESSED
 KEY_RELASED
 KEY_TYPED
Class declaration
 Following is the declaration for [Link] class:
public class KeyEvent extends InputEvent
Class methods

S.N. Method & Description


1 char getKeyChar()
Returns the character associated with the key in this event.
2 int getKeyCode()
Returns the integer keyCode associated with the key in this event.
3 int getKeyLocation()
Returns the location of the key that originated this key event.
4 static String getKeyModifiersText(int modifiers)
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".
5 static String getKeyText(int keyCode)
Returns a String describing the keyCode, such as "HOME", "F1" or "A".
6 boolean isActionKey()
Returns whether the key in this event is an "action" key.
7 String paramString()
Returns a parameter string identifying this event.
8 void setKeyChar(char keyChar)
Set the keyChar value to indicate a logical character.
9 void setKeyCode(int keyCode)
Set the keyCode value to indicate a physical key.
10 void setModifiers(int modifiers)
Deprecated. as of JDK1.1.4

Mouse Events
This event indicates a mouse action occurred in a component. This low-level event is
generated by a component object for Mouse Events and Mouse motion events.
 a mouse button is pressed
 a mouse button is released
 a mouse button is clicked (pressed and released)
 a mouse cursor enters the unobscured part of component's geometry
 a mouse cursor exits the unobscured part of component's geometry
 a mouse is moved
 the mouse is dragged
Class declaration
Following is the declaration for [Link] class:
public class MouseEvent extends InputEvent

Class methods
S.N. Method & Description
1 int getButton()
Returns which, if any, of the mouse buttons has changed state.
2 int getClickCount()
Returns the number of mouse clicks associated with this event.
3 Point getLocationOnScreen()
Returns the absolute x, y position of the event.
4 static String getMouseModifiersText(int modifiers)
Returns a String describing the modifier keys and mouse buttons that were down
during the event, such as "Shift", or "Ctrl+Shift".
5 Point getPoint()
Returns the x,y position of the event relative to the source component.
6 int getX()
Returns the horizontal x position of the event relative to the source component.
7 int getXOnScreen()
Returns the absolute horizontal x position of the event.
8 int getY()
Returns the vertical y position of the event relative to the source component.
9 int getYOnScreen()
Returns the absolute vertical y position of the event.
10 boolean isPopupTrigger() Returns whether or not this mouse event is the
popup menu trigger event for the platform.
11 String paramString()
Returns a parameter string identifying this event.
12 void translatePoint(int x, int y)
Translates the event's coordinates to a new position by adding specified x
(horizontal) and y (vertical) offsets.

Java AWT Panel


The class Panel is the simplest container class. It provides space in which an application can
attach any other component, including other panels. It uses FlowLayout as default layout
manager.
Following is the declaration for [Link] class:
public class Panel
extends Container
implements Accessible

Java Frames
A Frame is a resizable and movable window with a title bar and maximize, minimize and
close buttons. A Frame is a container that can have MenuBars, MenuItems and some other
components like label, button, textfield, radio button and so on

How to Create a Frame


A Frame can be created in one of two ways. By adapting any of the following two ways, we
will be able to get a Frame. The two ways are:
1. By following the simple concept of inheritance i.e., by extending the Frame
class. We will be considering this method in the article for demonstration
purposes and will get a brief idea of it.
2. By creating an object of the Frame class, in other words using association.

Methods of the Frame class


 setTitle(String value): This method provides a title to the Frame if not specified at
the time of object declaration of the Frame.

Frame [Link]("String value");


 String getTitle(): This method returns the title of the Frame.

String variable=Frame [Link]();


 setSize(int row,int col): This method sets the size of the Frame, row and column
wise.
void setSize(int row,int col);
 setVisible(boolean mode): It makes the Frame visible to us. If the parameter is "true"
then it will be visible otherwise if it is "False" then the Frame will not be visible.

void setVisible(boolean mode);


 setState(int state): It sets the state of the Frame as:

"0" for Normal state


"1" for iconified state i.e., minimized
"2" for deiconified state i.e., maximized

void setState(int state);


 setResizable(boolean mode): It sets the frame in the position that it can be resized or
can be fixed.

"true"- resizable
"False"- can not be resized.

public setResizable(boolean mode);


 setBackground([Link] name): It sets some specified color on the background
of the Frame.

Frame [Link]([Link] name);

Java Layout Managers

The Layout Managers are used to arrange components in a particular manner. The Java
Layout Managers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] etc.

Java Border Layout


The Border Layout is used to arrange the components in five regions: north, south, east, west,
and centre. Each region (area) may contain one component only. It is the default layout of a
frame or window. The Border Layout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Example of Border Layout class:
Using Border Layout (int hgap, int vgap) constructor

The following example inserts horizontal and vertical gaps between buttons using the
parameterized constructor Border Layout(int hgap, int gap)

FileName: [Link]

// import statement
import [Link].*;
import [Link].*;
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are placed
// in the frame
[Link](new BorderLayout(20, 15));
[Link](btn1, [Link]);
[Link](btn2, [Link]);
[Link](btn3, [Link]);
[Link](btn4, [Link]);
[Link](btn5, [Link]);
[Link](300,300);
[Link](true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}
Output:

Java GridLayout

The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout(int rows, int columns) Constructor

FileName: [Link]

import [Link].*;
import [Link].*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
// adding buttons to the frame
[Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5); [Link](b6);
[Link](b7); [Link](b8); [Link](b9);

// setting grid layout of 3 rows and 3 columns


[Link](new GridLayout(3,3));
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

Output:
Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Example of FlowLayout class: Using FlowLayout(int align, int hgap, int vgap)
constructor

FileName: [Link]

// import statement
import [Link].*;
import [Link].*;

public class FlowLayoutExample1


{
JFrame frameObj;
// constructor
FlowLayoutExample1()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");

// adding the buttons to frame


[Link](b1); [Link](b2); [Link](b3); [Link](b4);
[Link](b5); [Link](b6); [Link](b7); [Link](b8);
[Link](b9); [Link](b10);

// parameterized constructor is used


// where alignment is left
// horizontal gap is 20 units and vertical gap is 25 units.
[Link](new FlowLayout([Link], 20, 25));
[Link](300, 300);
[Link](true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample1();
}
}
Output:

Java AWT Button


A button is basically a control component with a label that generates an
event when pushed. The Button class is used to create a labeled button
that has platform independent implementation. The application result in
some action when the button is pushed.

When we press a button and release it, AWT sends an instance


of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then
it passes an action event by calling its own method processActionEvent.
This method passes the action event on to action listeners that are
interested in the action events generated by the button.

To perform an action on a button being pressed and released,


the ActionListener interface needs to be implemented. The registered
new listener can receive events from the button by
calling addActionListener method of the button. The Java application
can use the button's action command as a messaging protocol.

Java AWT Button Example with ActionListener


Example:
In the following example, we are handling the button click events by
implementing ActionListener Interface.

[Link]

// importing necessary libraries


import [Link].*;
import [Link].*;
public class ButtonExample3 {
public static void main(String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
TextField tf=new TextField();
[Link](50,50, 150,20);
// create instance of button with label
Button b=new Button("Click Here");
// set the position for the button in frame
[Link](50,100,60,30);
[Link](new ActionListener() {
public void actionPerformed (ActionEvent e) {
[Link]("Welcome to Javatpoint.");
}
});
// adding button the frame
[Link](b);
// adding textfield the frame
[Link](tf);
// setting size, layout and visibility
[Link](400,400);
[Link](null);
[Link](true);
}
}
Java AWT Label
The object of the Label class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by a programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is


accessed. To create a label, we need to create the object of Label class.

AWT Label Fields


The [Link] class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in
center.

Java AWT Label Example


In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.

[Link]

import [Link].*;

public class LabelExample {


public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


[Link](50, 100, 100, 30);
[Link](50, 150, 100, 30);

// adding labels to the frame


[Link](l1);
[Link](l2);

// setting size, layout and visibility of frame


[Link](400,400);
[Link](null);
[Link](true);
}
}

Java AWT TextField


The object of a TextField class is a text component that allows a user to
enter a single line text and edit it. It inherits TextComponent class,
which further inherits Component class.

When we enter a key in the text field (like key pressed, key released or
key typed), the event is sent to TextField. Then the KeyEvent is passed
to the registered KeyListener. It can also be done using ActionEvent; if
the ActionEvent is enabled on the text field, then the ActionEvent may be
fired by pressing return key. The event is handled by
the ActionListener interface.

// importing necessary libraries


import [Link].*;
import [Link].*;
// Our class extends Frame class and implements ActionListener interfa
ce
public class TextFieldExample2 extends Frame implements ActionLi
stener {
// creating instances of TextField and Button class
TextField tf1, tf2, tf3;
Button b1, b2;
// instantiating using constructor
TextFieldExample2() {
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
[Link](50, 50, 150, 20);
tf2 = new TextField();
[Link](50, 100, 150, 20);
tf3 = new TextField();
[Link](50, 150, 150, 20);
[Link](false);
b1 = new Button("+");
[Link](50, 200, 50, 50);
b2 = new Button("-");
[Link](120,200,50,50);
// adding action listener
[Link](this);
[Link](this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on button
s
public void actionPerformed(ActionEvent e) {
String s1 = [Link]();
String s2 = [Link]();
int a = [Link](s1);
int b = [Link](s2);
int c = 0;
if ([Link]() == b1){
c = a + b;
}
else if ([Link]() == b2){
c = a - b;
}
String result = [Link](c);
[Link](result);
}
// main method
public static void main(String[] args) {
new TextFieldExample2();
}
}

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

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSele
ctable, Accessible

Java AWT Checkbox Example


In the following example we are creating two checkboxes using the
Checkbox(String label) constructo and adding them into the Frame using
add() method.

[Link]

// importing AWT class


import [Link].*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
[Link](100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
[Link](100, 150, 50, 50);
// adding checkboxes to frame
[Link](checkbox1);
[Link](checkbox2);

// setting size, layout and visibility of frame


[Link](400,400);
[Link](null);
[Link](true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu

Java AWT Choice Example


In the following example, we are creating a choice menu using Choice()
constructor. Then we add 5 items to the menu using add() method and
Then add the choice menu into the Frame.

[Link]

// importing awt class


import [Link].*;
public class ChoiceExample1 {

// class constructor
ChoiceExample1() {

// creating a frame
Frame f = new Frame();

// creating a choice component


Choice c = new Choice();

// setting the bounds of choice menu


[Link](100, 100, 75, 75);

// adding items to the choice menu


[Link]("Item 1");
[Link]("Item 2");
[Link]("Item 3");
[Link]("Item 4");
[Link]("Item 5");

// adding choice menu to frame


[Link](c);

// setting size, layout and visibility of frame


[Link](400, 400);
[Link](null);
[Link](true);
}

// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}

Java AWT List


The object of List class represents a list of text items. With the help of the
List class, user can choose either one item or multiple items.

Java AWT List Example


In the following example, we are creating a List component with 5 rows and adding it into the
Frame.

[Link]

// importing awt class


import [Link].*;

public class ListExample1


{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);

// setting the position of list component


[Link](100, 100, 75, 75);

// adding list items into the list


[Link]("Item 1");
[Link]("Item 2");
[Link]("Item 3");
[Link]("Item 4");
[Link]("Item 5");

// adding the list to frame


[Link](l1);

// setting size, layout and visibility of frame


[Link](400, 400);
[Link](null);
[Link](true);
}

// main method
public static void main(String args[])
{
new ListExample1();
}
}

You might also like