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
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.
● Source: Events are generated from the source. There are various sources like
buttons, checkboxes, list, menu-item, 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.
Syntax: addTypeListener()
For KeyEvent we use addKeyListener() to register. And For ActionEvent we use
addActionListener() to register.
Event Classes in Java:
Event Class Listener Interface Description
ActionEvent ActionListener An event that indicates that a component-defined action occurred like a button click or
selecting an item from the menu-item list.
AdjustmentEvent AdjustmentListener The adjustment event is emitted by an Adjustable object like Scrollbar.
ComponentEvent ComponentListener An event that indicates that a component moved, the size changed or changed its visibility.
ContainerEvent ContainerListener When a component is added to a container (or) removed from it, then this event is
generated by a container object.
WindowEvent WindowListener An event which indicates whether a window has changed its status or not.
FocusEvent FocusListener These are focus-related events, which include focus, focusin, focusout, and
blur.
ItemEvent ItemListener An event that indicates whether an item was selected or not.
KeyEvent KeyListener An event that occurs due to a sequence of keypresses on the keyboard.
MouseEvent MouseListener & The events that occur due to the user interaction with the mouse (Pointing
MouseMotionListener Device).
MouseWheelEve MouseWheelListener An event that specifies that the mouse wheel was rotated in a component.
nt
TextEvent TextListener An event that occurs when an object’s text changes.
Different interfaces consists of different methods :
Listener Interface Methods
ActionListener · actionPerformed()
AdjustmentListener · adjustmentValueChanged()
ComponentListener · componentResized()
· componentShown()
· componentMoved()
· componentHidden()
ContainerListener · componentAdded()
· componentRemoved()
FocusListener · focusGained()
· focusLost()
ItemListener · itemStateChanged()
KeyListener · keyTyped()
· keyPressed()
· keyReleased()
MouseListener · mousePressed()
· mouseClicked()
· mouseEntered()
· mouseExited()
· mouseReleased()
MouseMotionListener · mouseMoved()
· mouseDragged()
MouseWheelListener · mouseWheelMoved()
TextListener · textChanged()
WindowListener · windowActivated()
· windowDeactivated()
· windowOpened()
· windowClosed()
· windowClosing()
Key Events
The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in [Link] package, and it has
three methods.
Sl. no. Method name Description
1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.
import [Link].*; //astract window toolkit // creating the text area
import [Link].*; area = new TextArea();
public class KeyListenerExample extends Frame implements KeyListener {
//setting the location of text area
Label l; [Link] (20, 80, 300, 300);
// adding the KeyListener to the text area
TextArea area;
[Link](this);
// class constructor // adding the label and text area to the
frame
KeyListenerExample() {
add(l);
// creating the label
add(area);
l = new Label(); // setting the size, layout and visibility of
frame
// setting the location of the label in frame
setSize (400, 400);
[Link] (20, 50, 100, 20);
setLayout (null);
setVisible (true);
// overriding the keyPressed() method of KeyListener interface where we set the text of the label when key is pressed
public void keyPressed (KeyEvent e) {
[Link] ("Key Pressed");
// overriding the keyReleased() method of KeyListener interface where we set the text of the label when key is released
public void keyReleased (KeyEvent e) {
[Link] ("Key Released");
// overriding the keyTyped() method of KeyListener interface where we set the text of the label when a key is typed
public void keyTyped (KeyEvent e) {
[Link] ("Key Typed");
// main method
public static void main(String[] args) {
new KeyListenerExample(); }}
Mouse Events
The Java MouseListener is notified whenever you change the state of mouse.
It is notified against MouseEvent. The MouseListener interface is found in
[Link] package. It has five methods.
mouseClicked(MouseEvent e);
mouseEntered(MouseEvent e);
mouseExited(MouseEvent e);
mousePressed(MouseEvent e);
mouseReleased(MouseEvent e);
import [Link].*; public void mouseClicked(MouseEvent e) {
import [Link].*; [Link]("Mouse Clicked"); }
public class MouseListenerExample extends Frame implements public void mouseEntered(MouseEvent e) {
MouseListener{ [Link]("Mouse Entered"); }
Label l; public void mouseExited(MouseEvent e) {
MouseListenerExample(){ [Link]("Mouse Exited"); }
addMouseListener(this); public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed"); }
l=new Label(); public void mouseReleased(MouseEvent e) {
[Link](20,50,100,20); [Link]("Mouse Released");
add(l); }
setSize(300,300); public static void main(String[] args) {
setLayout(null); new MouseListenerExample();
setVisible(true); } }
}
GUI(Graphical User Interface)
GUI, which stands for Graphical User Interface, is a user-friendly visual experience builder for Java applications. It comprises graphical
units like buttons, labels, windows, etc. via which users can connect with an application.
Swing(Swing is a GUI widget toolkit for Java ) and JavaFX (JavaFX is a set of graphics and media packages that enables developers to design,
create, test, debug, and deploy rich client applications )are two commonly used applications to create GUIs in Java.
Elements of GUI:
A GUI comprises an array of user interface elements. All these elements are displayed when a user is interacting with an
application and they are as follows:
1. Input commands such as buttons, check boxes, dropdown lists and text fields.
2. Informational components like icons, labels or notification dialogs.
3. Navigational units like menus, slidebars .
The JFrame class in [Link] package.
A frame is basically a window which is displayed whenever a user opens an application on his/her computer. It has
a title bar and buttons such as minimize, maximize and close along with other features.
The JFrame class consists of simple constructors such as JFrame() and JFrame(String). The JFrame() leaves the
frame’s title bar empty, whereas the JFrame(String) places the title bar to a specified text.
Apart from the title, the size of the frame can also be customized. It can be established by incorporating the
setSize(int, int) method by inserting the width and height desired for the frame. The size of a frame is always
designated in pixels.
For example, calling setSize(550,350) would create a frame that would be 550 pixels wide and 350 pixels tall.
Usually, frames are invisible at the time of their creation. However, a user can make them visible by using the
frame’s setVisible(boolean) method by using the word ‘true’ as an argument.
import [Link].*;
class gui{
public static void main(String args[]){
JFrame jframe = new JFrame("GUI Screen"); //create JFrame object
[Link](JFrame.EXIT_ON_CLOSE);// it
indicates the application to exit when the user closes the window.
[Link](400,400); //set size of GUI screen
[Link](true);
}
Adding buttons to the above frame. To create a component in Java, the user is required to create an object of that component’s class.
One such component to implement is JButton. This class represents the clickable buttons. In any application or program, buttons
trigger user actions. Literally, every action begins with a click; like to close an application, the user would click on the close button.
A swing can also be inserted, which can feature a text, a graphical icon or a combination of both. A user can use the following
constructors:
· JButton(String): This button is labelled with a specified text.
· JButton(Icon): This button is labelled with a graphical icon.
· JButton(String,Icon): This button is labelled with a combination of text and icon.
import [Link].*;
class gui{
public static void main(String args[]){
JFrame jframe = new JFrame("GUI Screen"); //create JFrame object
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400,400); //set size of GUI screen
JButton pressButton = new JButton("Click me"); //create JButton object
[Link]().add(pressButton);
[Link](true);
}}
getContentPane():This method returns the Container object that holds the content of the frame. The content pane is the area where you can
add various Swing components.
add(pressButton): This method adds the specified component (pressButton) to the content pane of the frame.
The JPanel class in [Link] package.
The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.
JPanel()
It is used to create a new JPanel with a double buffer and a flow layout.
JPanel(boolean isDoubleBuffered)
It is used to create a new JPanel with FlowLayout and the specified buffering strategy.
JPanel(LayoutManager layout)
It is used to create a new JPanel with the specified layout manager.
import [Link].*;
import [Link].*; public static void main(String args[])
public class PanelExample { {
PanelExample() new PanelExample();
{ }
JFrame f= new JFrame("Panel Example"); }
JPanel panel=new JPanel();
[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
[Link](50,100,80,30);
[Link]([Link]);
JButton b2=new JButton("Button 2");
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);
[Link](400,400);
Layout Managers(Flow ,Border ,Grid)
Layout Manager
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.
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.
You can create the flow layout either on left,right,center etc
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
Example for FlowLayout():
import [Link].*;
import [Link].*;
[Link](300, 300);
public class FlowLayoutExample [Link](true);
{ }
JFrame frameObj= new JFrame("Flow Layout Example");
public static void main(String argvs[])
FlowLayoutExample() // constructor {
{ FlowLayoutExample fl= new
FlowLayoutExample();
// creating the buttons }
JButton b1 = new JButton("HII"); }
JButton b2 = new JButton("WELCOME");
JButton b3 = new JButton("BYE");
// adding the buttons to frame
Example for FlowLayout(int align):
import [Link].*; [Link](300, 300);
import [Link].*; [Link](true);
}
public class FlowLayoutExample
{ public static void main(String argvs[])
JFrame frameObj= new JFrame("Flow Layout Example"); {
FlowLayoutExample fl= new
FlowLayoutExample() // constructor FlowLayoutExample();
{ }
}
// creating the buttons
JButton b1 = new JButton("HII");
JButton b2 = new JButton("WELCOME");
JButton b3 = new JButton("BYE");
// adding the buttons to frame
Example for FlowLayout(int align,int hgap,int vgap):
import [Link].*;
import [Link].*;
[Link](300, 300);
public class FlowLayoutExample [Link](true);
{ }
JFrame frameObj= new JFrame("Flow Layout Example");
public static void main(String argvs[])
FlowLayoutExample() // constructor {
{ FlowLayoutExample fl= new
FlowLayoutExample();
// creating the buttons }
JButton b1 = new JButton("HII"); }
JButton b2 = new JButton("WELCOME");
JButton b3 = new JButton("BYE");
// adding the buttons to frame
Layout Manager
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.
Constructors of BorderLayout class
1. BorderLayout(): creates a border layout but with no gaps between the
components.
2. BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Example for BorderLayout():
import [Link].*;
import [Link].*;
public class Border {
JFrame f;
Border()
JFrame f = new JFrame("BorderLayout Example");
JButton b1 = new JButton("NORTH");// the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("CENTER");
JButton b4 = new JButton("EAST");
JButton b5 = new JButton("WEST");
[Link](new BorderLayout());
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]);
[Link](b3, [Link]);
[Link](b4, [Link]);
[Link](b5, [Link]);
[Link](300, 300);
[Link](true);
}
public static void main(String args[]) {
Border b=new Border();
}
}
Example for BorderLayout(int hgap, int vgap):
import [Link].*;
import [Link].*;
public class Border {
JFrame f;
Border()
JFrame f = new JFrame("BorderLayout Example");
JButton b1 = new JButton("NORTH");// the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("CENTER");
JButton b4 = new JButton("EAST");
JButton b5 = new JButton("WEST");
[Link](new BorderLayout(20,15));
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]);
[Link](b3, [Link]);
[Link](b4, [Link]);
[Link](b5, [Link]);
[Link](300, 300);
[Link](true);
}
public static void main(String args[]) {
Border b=new Border();
}
}
Layout Manager
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
Example for GridLayout():
import [Link].*; [Link](new
import [Link].*; GridLayout());
public class GridLayoutExample{ [Link](300, 300);
JFrame f; [Link](true);
GridLayoutExample(){ }
f=new JFrame(); public static void main(String argvs[])
JButton b1=new JButton("1"); JButton b2=new JButton("2");
{
JButton b3=new JButton("3"); JButton b4=new JButton("4");
GridLayoutExample g=new
JButton b5=new JButton("5"); JButton b6=new JButton("6");
GridLayoutExample();
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);
Example for GridLayout(int rows, int columns):
import [Link].*; [Link](new
import [Link].*; GridLayout(3,3));
public class GridLayoutExample{ [Link](300, 300);
JFrame f; [Link](true);
GridLayoutExample(){ }
f=new JFrame(); public static void main(String args[])
JButton b1=new JButton("1"); JButton b2=new JButton("2"); {
JButton b3=new JButton("3"); JButton b4=new JButton("4"); GridLayoutExample g=new
GridLayoutExample();
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
//3 rows and 3 columns
[Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5); [Link](b6);
Example for GridLayout(int rows, int columns,int hgap,int vgap):
import [Link].*; [Link](new
import [Link].*; GridLayout(3,3,20,25));
public class GridLayoutExample{ [Link](300, 300);
JFrame f; [Link](true);
GridLayoutExample(){ }
f=new JFrame(); public static void main(String argvs[])
JButton b1=new JButton("1"); JButton b2=new JButton("2"); {
JButton b3=new JButton("3"); JButton b4=new JButton("4");GridLayoutExample g=new
GridLayoutExample();
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
//3 rows and 3 columns
[Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5); [Link](b6);
Label:
import [Link].*; [Link](null);
public class LabelExample { [Link](true);
public static void main(String args[]){
// set the location of label
Frame f = new Frame ("Label example");
[Link](50, 100, 100, 30);
Label l1, l2;
[Link](50, 150, 100, 30);
// initializing the labels
// adding labels to the frame
l1 = new Label ("First Label.");
[Link](l1);
l2 = new Label ("Second Label.");
[Link](l2);
// setting size, layout and visibility of frame
}}
[Link](400,400);
// set the location of label
Button: [Link](50, 100, 100, 30);
[Link](50, 150, 100, 30);
import [Link].*; // adding labels to the frame
public class ButtonExample { [Link](b1);
[Link](b2);
public static void main(String args[]){ }
}
Frame f = new Frame ("Button example");
Button b1, b2;
// initializing the labels
b1 = new Button ("Login");
b2 = new Button ("Logout");
// setting size, layout and visibility of frame
[Link](400,400);
[Link](null);
[Link](true);