Event Handling in Java
Event Handling in Java
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.
Delegation Event model
It has Sources and Listeners.
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.
Changing the state of an object is known as an event. For example, click on button,
java.awt.event package provides many event classes and Listener interfaces for event handlin
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the component it may be
button, textfield etc.
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.
Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField, ChechBox,
button, etc.
For example, an AWT GUI with components like TextField, label and button
will have different look and feel for the different platforms like Windows, MAC
OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates
those components.
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
Container
It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void setSize(int width,int Sets the size (width and height) of the
height) component.
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
To create simple AWT example, you need a frame. There are two ways to
create a GUI using Frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
// importing Java AWT class
import java.awt.*;
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the
above example that sets the position of the awt button.
Output:
ButtonExample.java
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
To compile the program using command prompt type the following commands
1. C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java
1. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:
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.
Output:
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
// class constructor
ScrollbarExample1() {
// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();
// main method
public static void main(String args[]) {
new ScrollbarExample1();
}
}
Output:
The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the
text area becomes larger than the viewable area, the scroll bar appears
automatically which helps us to scroll the text up and down, or right and left.
1 void append(String str) It appends the specified text to the current text of
text area.
4 void insert(String str, int It inserts the specified text at the specified position
pos) in this text area.
5 void setColumns(int It sets the number of columns for this text area.
columns)
TextAreaExample2() {
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
Output:
Java AWT CheckboxGroup
In the following example, we have created two checkboxes and adding them
into the Frame. Here, we are adding the ItemListener with the checkbox which
displays the state of the checkbox (whether it is checked or unchecked) using
the getStateChange() method.
CheckboxExample2.java
ckbox1);
f.add(checkbox2);
f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"uncheck
ed") } });
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CheckboxExample2();
}
}
Output:
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits
the Component class.
Class methods
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
ss f.add(new MyCanvas());
// main method
public static void main(String args[])
{
new CanvasExample();
}
}
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Output:
In the following example, we are creating a choice menu with 5 items. Along
with that we are creating a button and a label. Here, we are adding an event to
the button component using addActionListener(ActionListener a) method i.e.
the selected item from the choice menu is displayed on the label when the
button is clicked.
ExampleChoice.java
// main method
public static void main(String args[])
{
new ExampleChoice( );
}
}
Output:
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. It inherits the
Component class.
In the following example, we are creating two List components, a Button and a
Label and adding them into the frame. Here, we are generating an event on the
button using the addActionListener(ActionListener l) method. On clicking the
button, it displays the selected programming language and the framework.
ListExample2.java
// importing awt and event class
import java.awt.*;
import java.awt.event.*;
// creating a button
Button b = new Button("Show");
// main method
public static void main(String args[])
{
new ListExample2();
}
}
Output:
Java AWT Panel
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.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
BorderLayout (LayoutManagers)
Java LayoutManagers
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
Java BorderLayout
FileName: Border.java
import java.awt.*;
import javax.swing.*;
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as N
ORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SO
UTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAS
T
JButton b4 = new JButton("WEST");; // the button will be labeled as WES
T
JButton b5 = new JButton("CENTER");; // the button will be labeled as C
ENTER
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
Java GridLayout
// import statements
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
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.
// import statements
import java.awt.*;
import javax.swing.*;
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
Java CardLayout
The Java CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a card that
is why it is known as CardLayout.
The following program uses the next() method to move to the next card of the
container.
FileName: CardLayoutExample1.java
// import statements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
CardLayout crd;
cPane = getContentPane();
cPane.setLayout(crd);
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon click
ing
crd.next(cPane);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();
Output:
Java GridBagLayout
The components may not be of the same size. Each GridBagLayout object
maintains a dynamic, rectangular grid of cells. Each component occupies one or
more cells known as its display area. Each component associates an instance of
GridBagConstraints.
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridsy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Output:
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-
generic. Now generics force the java programmer to store a specific type of
objects.
ClassOrInterface<Type>
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
import java.util.*;
class TestGenerics2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"vijay");
map.put(4,"umesh");
map.put(2,"ankit");
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
while(itr.hasNext()){
Map.Entry e=itr.next();//no need to typecast
System.out.println(e.getKey()+" "+e.getValue());
}
}}
Output
1 vijay
2 ankit
4 umesh
Generic class
A class that can refer to any type is known as a generic class. Here, we are using
the T type parameter to create the generic class of specific type.
Let's see a simple example to create and use the generic class.
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, and
Employee). The type you specify for the class will be used to store and retrieve
the data.
class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}
Output
Type Parameters
The type parameters naming conventions are important to learn generics
thoroughly. The common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like the generic class, we can create a generic method that can accept any type of
arguments. Here, the scope of arguments is limited to the method where it is
declared. It allows static as well as non-static methods.
Let's see a simple example of java generic method to print array elements. We are
using here E to denote the element.
Output
Printing Integer Array
10
20
30
40
50
Printing Character Array
J
A
V
A