0% found this document useful (0 votes)
2 views

Unit 3 Java

This document provides an overview of threads in Java, detailing their lifecycle, creation methods, and synchronization techniques. It explains the various states of a thread, how to create threads using the Thread class and Runnable interface, and the importance of synchronization to prevent resource conflicts. Additionally, it covers inter-thread communication, AWT components for GUI development, and the hierarchical structure of components in Java AWT.

Uploaded by

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

Unit 3 Java

This document provides an overview of threads in Java, detailing their lifecycle, creation methods, and synchronization techniques. It explains the various states of a thread, how to create threads using the Thread class and Runnable interface, and the importance of synchronization to prevent resource conflicts. Additionally, it covers inter-thread communication, AWT components for GUI development, and the hierarchical structure of components in Java AWT.

Uploaded by

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

Unit 3

1. Threads

Typically, we can define threads as a sub-process with lightweight with the smallest unit of
processes and also has separate paths of execution. The main advantage of multiple threads is
efficiency (allowing multiple things at the same time. For example, in MS Word, one thread
automatically formats the document while another thread is taking user input. Another
advantage is quick response, if we use multiple threads in a process and if a thread gets stuck
due to lack of resources or an exception, the other threads can continue to execution, allowing
the process (which represents an application) to continue to be responsive.
In a simple way, a Thread is a:
o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Life Cycle of Thread

There are different states Thread transfers into during its lifetime, let us know about those states
in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State

New State

By default, a Thread will be in a new state, in this state, code has not yet been run and the
execution process is not yet initiated.

Active State

A Thread that is a new state by default gets transferred to Active state when it invokes the start()
method, his Active state contains two sub-states namely:

• Runnable State: In This State, The Thread is ready to run at any given time and it’s the
job of the Thread Scheduler to provide the thread time for the runnable state preserved
threads. A program that has obtained Multithreading shares slices of time intervals which
are shared between threads hence, these threads run for some short span of time and wait in
the runnable state to get their schedules slice of a time interval.
• Running State: When The Thread Receives CPU allocated by Thread Scheduler, it
transfers from the “Runnable” state to the “Running” state. and after the expiry of its given
time slice session, it again moves back to the “Runnable” state and waits for its next time
slice.
Waiting/Blocked State

If a Thread is inactive but on a temporary time, then either it is a waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 needs to communicate to the camera and
the other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its
work, at this state T1 is parked in waiting for the state, and in another scenario, the user called
two Threads T2 and T3 with the same functionality and both had same time slice given by
Thread Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple
threads parked in a Blocked/Waiting state Thread Scheduler clears Queue by rejecting
unwanted Threads and allocating CPU on a priority basis.

Timed Waiting State

Sometimes the longer duration of waiting for threads causes starvation, if we take an example
like there are two threads T1, T2 waiting for CPU and T1 is undergoing a Critical Coding
operation and if it does not exist the CPU until its operation gets executed then T2 will be
exposed to longer waiting with undetermined certainty, In order to avoid this starvation
situation, we had Timed Waiting for the state to avoid that kind of scenario as in Timed Waiting,
each thread has a time period for which sleep() method is invoked and after the time expires the
Threads starts executing its task.

Terminated State

A thread will be in Terminated State, due to the below reasons:


• Termination is achieved by a Thread when it finishes its task normally.
• Sometimes Threads may be terminated due to unusual events like segmentation faults,
exceptions…etc. and such kind of Termination can be called Abnormal Termination.
• A terminated Thread means it is dead and no longer available.

2. How to Create Threads using Java Programming Language?

We can create Threads in java using two ways, namely:


1. Extending Thread Class
2. Implementing a Runnable interface

1. By Extending Thread Class

We can run Threads in Java by using Thread Class, which provides constructors and methods
for creating and performing operations on a Thread, which extends a Thread class that can
implement Runnable Interface. We use the following constructors for creating the Thread:
• Thread
• Thread(Runnable r)
• Thread(String name)
• Thread(Runnable r, String name)
import java.io.*;
import java.util.*;

public class GFG extends Thread {


// initiated run method for Thread
public void run()
{
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{
GFG g1 = new GFG();

// Invoking Thread using start() method


g1.start();
}
}

2. Runnable Interface
import java.io.*;
import java.util.*;

public class GFG implements Runnable {


// method to start Thread
public void run()
{
System.out.println(
"Thread is Running Successfully");
}

public static void main(String[] args)


{
GFG g1 = new GFG();
// initializing Thread Object
Thread t1 = new Thread(g1);
t1.start();
}
}

3. Thread Synchronization
Multi-threaded programs may often come to a situation where multiple threads try to access
the same resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.
Java Synchronized Blocks
Java provides a way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at a time.
All other threads attempting to enter the synchronized block are blocked until the thread inside
the synchronized block exits the block.

General form of Synchronised Block


synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}

This synchronization is implemented in Java with a concept called monitors or locks. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be suspended
until the first thread exits the monitor.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes.
It ensures that the shared resources are safe and in order.
2. Thread Synchronization in Java
Thread Synchronization is used to coordinate and ordering of the execution of the threads in a
multi-threaded program. There are two types of thread synchronization are mentioned below:
• Mutual Exclusive
• Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
There are three types of Mutual Exclusive mentioned below:
• Synchronized method.
• Synchronized block.
• Static synchronization.

import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


S1.start();
S2.start();
// wait for threads to end
try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}

Java Pogram to synchronized method by using an anonymous class


import java.io.*;

class Test {
synchronized void test_function(int n)
{
// synchronized method
for (int i = 1; i <= 3; i++) {
System.out.println(n + i);
try {
Thread.sleep(500);
}
catch (Exception e) {
System.out.println(e);
}
}
}
}

// Driver Class
public class GFG {
// Main function
public static void main(String args[])
{
// only one object
final Test obj = new Test();

Thread a = new Thread() {


public void run() { obj.test_function(15); }
};

Thread b = new Thread() {


public void run() { obj.test_function(30); }
};
a.start();
b.start();
}
}

4. Thread Communication
Inter-thread communication in Java is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed. Inter-thread communication is also known as Cooperation in Java.
The process of testing a condition repeatedly till it becomes true is known as polling. Polling is
usually implemented with the help of loops to check whether a particular condition is true or
not. If it is true, a certain action is taken. This wastes many CPU cycles and makes the
implementation inefficient.
For example, in a classic queuing problem where one thread is producing data, and the other is
consuming it.
How Java multi-threading tackles this problem?

To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these
methods belong to object class as final so that all classes have them. They must be used within
a synchronized block only.
• wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
• notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
• notifyAll(): It wakes up all the threads called wait() on the same object.

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.
Difference between wait and sleep
Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

Example:

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}

5. AWT Components
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications. AWT
is heavyweight, which means that its components consume resources from the underlying
operating system (OS). The java.awt package contains AWT API classes such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Why AWT is Platform Independent?

The Java AWT utilizes the native platform subroutine to create API components such as
TextField, CheckBox, and buttons. This results in a different visual format for these
components on different platforms such as Windows, MAC OS, and Unix. The reason for this
is that each platform has a distinct view of its native components. AWT directly calls this native
subroutine to create the components, resulting in an AWT application resembling a Windows
application on Windows OS, and a Mac application on the MAC OS. In simpler terms, the AWT
application’s appearance adapts to the platform it is running on.
AWT is platform independent even after the AWT components are platform dependent because
of the points mentioned below:

1. JVM (Java Virtual Machine):


As Java Virtual Machine is platform dependent

2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract
API which are platform independent. Abstract API allows Java to isolate platform-specific
details, making code portable across different systems.

3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent. Because
of this, it ensures that AWT functionality remains consistent across different environments.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
• Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
• Containers: AWT provides containers like panels, frames, and dialogues to organize and
group components in the Application.
• Layout Managers: Layout Managers are responsible for arranging data in the containers
some of the layout managers are BorderLayout, FlowLayout, etc.
• Event Handling: AWT allows the user to handle the events like mouse clicks, key presses,
etc. using event listeners and adapters.
• Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images
and write text in the components of a Java Application.
5. Component Class
The Component class is the superclass of all components. A component class can be linked with
a page, components of web applications. Component clearly shows that is the graphical
representation of an Object.

Important methods of Component Class:

1. public void add(Component c): This method inserts a component into a Container by
taking a component as a parameter.
2. public void setSize(int width, int height): This method sets the size of the component by
taking height and width as parameters.
3. public void setLayout(LayoutManager lm): This method sets the layout to set the
components in a particular manner by taking LayoutManager as a parameter.
4. public void setVisible(boolean status): This method sets the visibility of a component to
visible or not. If it sets to true then the component will be visible in the output else if it sets
to false or not defined component won’t be visible in the output.
Types of Components in Component Class
1. Container
2. Button
3. Label
4. Checkbox
5. Choice
6. List

All these components are present in java.awt package. We can import each of the components
individually i.e., import java.awt.Button, import java.awt.Container etc.

Hierarchical Structure of Components

Container

The Container is a component that will be used to extend other components such as window,
panel, Frame, Dialog, and Applet as shown in the above diagram.
• Window: The Window is a Container that doesn’t include borders and a menu bar. We
must use another window, frames, and dialogue box to create a Window. Creating an
instance is the way to create a Window Container.
• Panel: The Panel is also a Container that doesn’t include a title bar, menu, or border. It is
a container that holds components like buttons, textfield, etc. Creating an instance is the
way to create a Panel Container and can add components.
• Frame: The Frame is a container used while creating an AWT application. It can have
components like title bar, menu bars, borders and also buttons, scroll bar, etc.
• Dialog: The Dialog box is a container that will display the message that we want to display
on the screen.
Button

A button is a labeled component when clicked performs an event. It is created by the Button
class. When clicked it performs some action by sending an instance of ActionEvent by AWT.
ActionEvent calls processEvent on the button and it receives all the events and performs action
by calling the processActionEvent method of its own. To do such things it needs to implement
ActionListener. The Declaration of Button Class will be
public class Button extends Component implements Accessible
It contains 2 constructors:
1. Button() : This constructor will create a button with no label
2. Button(String label) : This constructor creates a button with label value as a value when
we creates an object
Label

It is used to show text in the Container. It will displays text in the form of READ-ONLY, which
cannot be changed by the user directly. We need to create an instance of Label Class to create
a Label. The Declaration of Label Class will be
public class Label extends Component implements Accessible
It has 3 constructors:
1. Label() : Creates an Empty Label.
2. Label(String labelname) : Creates a Label with labelname as parameter value.
3. Label(String labelname, int align) : Creates a Label with labelname as parameter value
and proper alignments.
It is used to create a Checkbox in the Container. It can get a value either true or false by checking
and unchecking the checkbox.
• checked – returns true
• unchecked – returns false
It can be created by creating an instance of Checkbox. The Declaration of Label Class will be
public class Checkbox extends Component implements ItemSelectable, Accessible
It has 5 constructors:
1. Checkbox() : Creates a checkbox with empty label
2. Checkbox(String checkboxlabel) : Creates a Checkbox with checkboxlabel as parameter
value.
3. Checkbox(String checkboxlabel, boolean status) : Creates a Checkbox with checkboxlabel
as parameter value and sets the status either true or false.
4. Checkbox(String checkboxlabel, boolean status, CheckboxGroup cbgroup) : Creates a
Checkbox with checkboxlabel as parameter value and sets the status to the specified
checkbox group.
5. Checkbox(String checkboxlabel, CheckboxGroup cbgroup, boolean status) : Creates a
Checkbox with checkboxlabel as parameter value for the specified cbgroup and sets the
status.
/ importing AWT class
import java.awt.*;

public class CourseCheck {


// main method
public static void main(String args[])
{
// creating the frame with the label
Frame frame = new Frame("Courses");

// creating checkbox java


Checkbox java = new Checkbox("Java");

// setting location of checkbox in frame


java.setBounds(100, 100, 50, 50);

// creating checkbox python with status as true


Checkbox python = new Checkbox("Python", true);

// setting location of checkbox in frame


python.setBounds(100, 150, 50, 50);

// adding checkboxes to frame


frame.add(java);
frame.add(python);

// setting size, layout and


// visibility of frame
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
}
}

5. Choice

It is used to show the popup menu to select any item from the menu items. The selected choice
will be shown at the top of the menu bar. We need to create an instance of Choice Class to
create a Choice. The Declaration of Choice Class will be
public class Choice extends Component implements ItemSelectable, Accessible
It has 1 constructor:
Choice() : Creates a new Choice menu of items

import java.awt.*;
public class SelectItems {

// main method
public static void main(String args[])
{
// creating a Frame
Frame frame = new Frame();

// creating a choice component


Choice choice = new Choice();

// setting the bounds of choice menu


choice.setBounds(70, 70, 75, 75);

// adding items to the choice menu


choice.add("--select--");
choice.add("Shampoo");
choice.add("Eggs");
choice.add("Bottles");

// adding choice menu to frame


frame.add(choice);

// setting size, layout


// and visibility of frame
frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);
}

The List Object creates a list of items in which we can choose one or multiple items at a time.
We need to create an instance of List Class to create a List. The Declaration of Label Class will
be
public class List extends Component implements ItemSelectable, Accessible

It has 3 constructors:
1. List() : Creates a new Scrolling List
2. List(int noofrows) : Creates a new Scrolling List which displays the list of items with
given no. of rows visible with parameter noofrows.
3. List(int noofrows, boolean multi) : Creates a new Scrolling list which displays the list of
items with given no. of rows visible and allows to select multiple items at a time.
import java.awt.*;
public class SelectList {

// main method
public static void main(String args[])
{
// creating frame1
Frame frame1 = new Frame();

// creating list1 with 5 rows


List list1 = new List(5);
// setting the position of list component
list1.setBounds(100, 100, 75, 75);

// adding list items to the list1


list1.add("Shampoo");
list1.add("Conditioner");
list1.add("Eggs");
list1.add("Bottles");
list1.add("Butter");

// adding the list1 to frame1


frame1.add(list1);

// setting size, layout


// and visibility of frame1
frame1.setSize(400, 400);
frame1.setLayout(null);
frame1.setVisible(true);

// creating frame2
Frame frame2 = new Frame();

// creating list2 with 5 rows


// and multi select items as true
List list2 = new List(5, true);

// setting the position of list component


list2.setBounds(100, 100, 75, 75);

// adding list items to the list2


list2.add("Shampoo");
list2.add("Conditioner");
list2.add("Eggs");
list2.add("Bottles");
list2.add("Butter");

// adding the list2 to frame2


frame2.add(list2);

// setting size, layout


// and visibility of frame2
frame2.setSize(400, 400);
frame2.setLayout(null);
frame2.setVisible(true);
}
}

6. Layout Manager

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.
Layout Manager is an interface that is implemented by all the classes of layout managers. There
are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java 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:
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

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Flow Layout
Flow Layout is a simple layout manager that arranges components in a row, left to right, wrapping
to the next line as needed. It is ideal for scenarios where components need to maintain their natural
sizes and maintain a flow-like structure.
import javax. swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Grid Layout
Grid Layout arranges components in a grid with a specified number of rows and columns. Each cell
in the grid can hold a component. This layout manager is ideal for creating a uniform grid of
components, such as a calculator or a game board.

import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
frame.add(new JButton("Button " + i));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Card Layout
Card Layout allows components to be stacked on top of each other, like a deck of cards. Only one
component is visible at a time, and you can switch between components using methods like next()
and previous(). This layout is useful for creating wizards or multi-step processes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
JButton button1 = new JButton("Card 1");
JButton button2 = new JButton("Card 2");
JButton button3 = new JButton("Card 3");
cardPanel.add(button1, "Card 1");
cardPanel.add(button2, "Card 2");
cardPanel.add(button3, "Card 3");
frame.add(cardPanel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
}
}

GroupLayout
GroupLayout is a versatile and complex layout manager that provides precise control over the
positioning and sizing of components. It arranges components in a hierarchical manner using
groups. GroupLayout is commonly used in GUI builders like the one in NetBeans IDE.
import javax.swing.*;
public class GroupLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GroupLayout Example");
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(button1)
.addComponent(button2));
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(button1)
.addComponent(button2));
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create complex layouts by
specifying constraints for each component. It arranges components in a grid, but unlike
GridLayout, it allows components to span multiple rows and columns and have varying sizes.
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Example");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(button1, constraints);
constraints.gridx = 1;
panel.add(button2, constraints);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

7. AWT Events
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 java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
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.


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
ActionEvent ActionListener
like a button click or selecting an item
from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size changed or
changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
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.
Event Class Listener Interface Description

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.

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.

Code-Approaches

The three approaches for performing event handling are by placing the event handling code in
one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class

Java program to demonstrate the event handling within the class

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

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}

Java program to demonstrate the event handling by the other class

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

class GFG1 extends Frame {

TextField textField;

GFG2()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
button.addActionListener(other);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}

Java program to demonstrate the event handling by the anonymous class

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

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener anonymously


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("Anonymous");
}
});

// add Components
add(textField);
add(button);

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}

The Event listener represent the interfaces responsible to handle events. Java provides us various
Event listener classes but we will discuss those which are more frequently used. Every method of
an event listener method has a single argument as an object which is subclass of EventObject class.
For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.
EventListner interface
It is a marker interface which every listener interface has to extend.This class is defined in java.util
package.
Class declaration
Following is the declaration for java.util.EventListener interface:
public interface EventListener
AWT Event Listener Interfaces:
Following is the list of commonly used event listeners.
Sr. No. Control & Description

ActionListener
1
This interface is used for receiving the action events.

ComponentListener
2
This interface is used for receiving the component events.

3 ItemListener
This interface is used for receiving the item events.

KeyListener
4
This interface is used for receiving the key events.

MouseListener
5
This interface is used for receiving the mouse events.

TextListener
6
This interface is used for receiving the text events.

WindowListener
7
This interface is used for receiving the window events.

AdjustmentListener
8
This interface is used for receiving the adjusmtent events.

ContainerListener
9
This interface is used for receiving the container events.

MouseMotionListener
10
This interface is used for receiving the mouse motion events.

FocusListener
11
This interface is used for receiving the focus events.
8. Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Pros of using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener
MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Example:

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

public class AdapterExample {


// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}

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

Java MouseAdapter Example


In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.
MouseAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;

// class which inherits the MouseAdapter class


public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using getGraphics() method

Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}

You might also like