Event Handling in Java
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 [Link] package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events
Types of 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.
Delegation Event model
It has Sources and Listeners.
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.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java
Event Class Listener Interface Description
An event that indicates that a
component-defined action occurred like
ActionEvent ActionListener
a button click or selecting an item from
the menu-item list.
Event Class Listener Interface Description
The adjustment event is emitted by an
AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.
An event that indicates that a component
ComponentEvent ComponentListener moved, the size changed or changed its
visibility.
When a component is added to a
ContainerEvent ContainerListener container (or) removed from it, then this
event is generated by a container object.
These are focus-related events, which
FocusEvent FocusListener include focus, focusin, focusout, and
blur.
An event that indicates whether an item
ItemEvent ItemListener
was selected or not.
An event that occurs due to a sequence
KeyEvent KeyListener
of keypresses on the keyboard.
The events that occur due to the user
MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).
An event that specifies that the mouse
MouseWheelEvent MouseWheelListener
wheel was rotated in a component.
An event that occurs when an object’s
TextEvent TextListener
text changes.
An event which indicates whether a
WindowEvent WindowListener
window has changed its status or not.
Note: As Interfaces contains abstract methods which need to implemented by the
registered class to handle events.
Different interfaces consists of different methods which are specified below.
Listener Interface Methods
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
MouseMotionListene mouseMoved()
r mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
WindowListener windowActivated()
windowDeactivated()
Listener Interface Methods
windowOpened()
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
Flow of Event Handling
1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.
.
import [Link].*;
import [Link];
import [Link];
public class Myevent extends Frame implements MouseListener{
int x=100,y=100;
String msg=" ";
public Myevent()
{
[Link](this);
}
public void paint(Graphics g)
{
[Link](msg, x,y);
}
public static void main(String[] args)
{
Myevent f1=new Myevent();
[Link](400,400);
[Link](true);
[Link]("my first Frame");
}
@Override
public void mouseClicked(MouseEvent e) {
x=[Link]();
y=[Link]();
msg="mouse clicked at "+x + ","+ y ;
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
msg="mouse entered at ";
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
msg="mouse exit at ";
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
// x=[Link]();
// y=[Link]();
msg="mouse pressed at ";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
// x=[Link]();
// y=[Link]();
msg="mouse re at released";
repaint();
Copying character from one file to another
import [Link].*;
public class copyfile {
public static void main(String[] args) throws IOException
{
File infile=new File("[Link]");
File outfile= new File("[Link]");
FileReader ins =new FileReader(infile);
FileWriter outs= new FileWriter(outfile);
int ch;
while((ch=[Link]( ))!=-1)
{
[Link](ch);
[Link]();
[Link]();
}
}
This program creates two objects infile and outfile and initializes them with ‘[Link]’ and
‘[Link]’
File infile=new File("[Link]");
File outfile= new File("[Link]");
The program then creates two file stream object ins and outs and connect to the named file
using following code
FileReader ins =new FileReader(infile);
FileWriter outs= new FileWriter(outfile);
This connect infile to the FileReader stream ins and outfile to FileWriter Stream outs.
This means [Link] and [Link] files are opened.
Ch= [Link]() reads a character from infile through the input stream ins and assigns it to the
variable ch. Similarly the statement [Link](ch) writes the character stored in the variable ch
to outfile through the output stream outs. The character -1 indicates the end of the file and the
code
while((ch=[Link]( ))!=-1)causes the termination of the while loop when the end of file is reached.
Statement [Link](); and [Link](); close the files created for readind and writing.
Output:
Note : first write some text in [Link]( which will appear in the program list).
Then run the program and check [Link] file in program list
LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers 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]
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.
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example:
import [Link].*;
public class flowlayout extends Frame
{
flowlayout(){
setLayout(new FlowLayout());
setSize(300,400);
setVisible(true);
Label l1= new Label("add");
Label l2=new Label("sub");
Label l3= new Label("mul");
Label l4=new Label("div");
add(l1);
add(l2);
add(l3);
add(l4);
}
public static void main(String[] args)
{
flowlayout fl=new flowlayout();
}
}
BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
o import [Link].*;
o public class borderlayout extends Frame
o {
o
o borderlayout(){
o setLayout(new BorderLayout());
o setSize(300,400);
o setVisible(true);
o add(new Button("add"),[Link]);
o add(new Button("sub"),[Link]);
o add(new Button("mul"),[Link]);
o add(new Button("div"),[Link]);
o add(new TextArea(),[Link] );
o }
o public static void main(String[] args)
o {
o borderlayout bl=new borderlayout();
o }
o }
o