ADVANCED JAVA PROGRAMMING
UNIT-1 NOTES
COMPONENTS AND EVENT HANDLING
AWT (Abstract Window Toolkit):
AWT represents a class library to develop applications using GUI. The [Link]
package consists of classes and interfaces to develop GUIs.
Component: A component represents an object which is displayed pictorially on the screen
and interacts with the user.
Ex. Button, TextField, TextArea
Container: A Container is a subclass of Component; it has methods that allow other
components to be nested in it. A container is responsible for laying out (that is positioning)
any component that it contains. It does this with various layout managers.
Panel: Panel class is a subclass of Container and is a super class of Applet. When screen
output is redirected to an applet, it is drawn on the surface of the Panel object. In, essence
panel is a window that does not contain a title bar, menu bar or border.
Window: A window represents a rectangular area on the screen without any borders or title
bar. The Window class create a top-level window.
Frame: It is a subclass of Window and it has title bar, menu bar, border and resizing
windows.
Delegation Event Model:
The modern approach (from version 1.1 onwards) to handle events is based on the delegation
event model. Its concept is quite simple: a source generates an event and sends it to one or
more listeners.
In this scheme, the listener simply waits until it receives an event. Once an event is received,
the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that
generates those events.
A user interface element is able to ―delegate‖ the processing of an event to a separate piece
of code. In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only
to listeners that want to receive them.
Events: An event is an object that describes a state change in a source. It can be generated as
a consequence of a person interacting with the elements in a GUI. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard,
selecting an item in a list, and clicking the mouse.
Event Sources: A source is an object that generates an event. Generally sources are
components. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the general
form:
public void addTypeListener (TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ).
A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )
Event Listeners: A listener is an object that is notified when an event occurs. It has two major
requirements.
1. It must have been registered with one or more sources to receive notifications about
specific types of events.
2. It must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
[Link] package.
Sources of Events:
Event Source Description
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Menu item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text Generates text events when the user enters a character.
components
Window Generates window events when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
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.
Delegation event model
⮚ The delegation model is a programming design pattern that is used to handle events and event-
driven programming in graphical user interfaces.
⮚ A source generates an event and forwards it to one or more listeners, where the listener waits
until they receive an event. Once the listener gets the event, it is processed by the listener, and
then they return it.
⮚ The advantage of this design is that a user interface element is able to “delegate” the
processing of an event to a separate piece of code.
⮚ It eliminates overhead.
Some popular java event classes and listener interfaces:
Event classes Listener interfaces Methods
ActionEvent ActionListener
● actionPerformed()
AdjustmentEvent AdjustmentListener
● adjustmentValueChanged()
ComponentEvent ComponentListener
● componentResized()
● componentShown()
● componentMoved()
● componentHidden()
2
ContainerEvent ContainerListener
● componentAdded()
● componentRemoved()
FocusEvent FocusListener
● focusGained()
● focusLost()
ItemEvent ItemListener
● itemStateChanged()
KeyEvent KeyListener
● keyTyped()
● keyPressed()
● keyReleased()
MouseEvent MouseListener
● mousePressed()
● mouseClicked()
● mouseEntered()
● mouseExited()
● mouseReleased()
MouseEvent MouseMotionListener
● mouseMoved()
● mouseDragged()
MouseWheelEvent MouseWheelListener
● mouseWheelMoved()
WindowEvent WindowListener
● windowActivated()
● windowDeactivated()
● windowOpened()
● windowClosed()
● windowClosing()
● windowIconified()
● windowDeiconified()
TextEvent TextListener
● textChanged()
Example:
import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components tf=new
TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
[Link](this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Output:
Threading concepts
Multithreading:
▪ Multithreading in Java is a process of executing multiple threads
simultaneously.
▪ Multiprocessing and multithreading, both are used to achieve multitasking.
▪ A Thread is a light-weighted process, or we can say the smallest part of the
process.
▪ It allows a program to operate more efficiently by running multiple tasks
simultaneously(parallel).
▪ It shares the same address space.
▪ Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads.
▪ Java Multithreading is mostly used in games, animation, etc.
Life cycle of a thread:
▪ Newborn state
▪ Runnable state
▪ Running state
▪ Blocked state
▪ Dead state
Newborn:
▪ Whenever a thread is created it is said to be newborn state.
▪ It is not yet scheduled for running.
▪ At this stage, we can do only one of the following:
1. Schedule it for running using start() method.
2. Kill it using stop() method.
Runnable:
▪ A thread, that is ready to run(Executing) is then moved to the runnable
state.
▪ It is waiting for the availability of the processor.
▪ The thread has joined the queue
Running:
▪ Thread is executing.
▪ When the thread gets the CPU, it moves from the runnable to the running
state.
▪ The thread runs until it gives up control on its own or taken over by other
threads.
Blocked:
▪ A thread is inactive(Blocked) for a span of time (not permanently).
▪ A blocked thread is considered ”not runnable” ,”not dead” and therefore
fully qualified to run again. It is known as blocked state or waiting state.
▪ This state is achieved when we invoke suspend() or sleep() or wait()
methods.
Dead:
▪ When a thread has finished its job, then it exists or terminates normally. It
is a natural death (normal).
▪ When a thread has killed in born or in running or even in runnable state, it
is called prematurn death (abnormal).
▪ This state is achieved when we invoke stop() method or when the thread
completes it execution.
Thread class creation:
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class (Thread class) and implements Runnable
interface.
Thread priority:
Each thread has a priority. Priorities are represented by a number between 1
and 10.
▪ The value of MIN_PRIORITY is 1.
▪ The value of NORM_PRIORITY is 5. (Default priority)
▪ The value of MAX_PRIORITY is 10.
getpriority():
The [Link]() method returns the priority of the given
thread.
setpriority():
▪ The [Link]() method updates or assign the priority of
the thread to new Priority.
▪ The method throws IllegalArgumentException if the value new Priority
goes out of the range, which is 1 (minimum) to 10 (maximum).
Here are some of the methods in the Thread class:
Methods Description
start() Starts the thread.
run() This method is executed when the thread starts.
sleep() Pauses the thread for a specified amount of time.
interrupt() Interrupts the thread.
join() Waits for the thread to die.
isAlive() Checks if the thread is alive.
getName() Gets the name of the thread.
setName() Sets the name of the thread.
getId() Gets the ID of the thread.
getPriority() Gets the priority of the thread.
setPriority() Sets the priority of the thread.
isDaemon() Checks if the thread is a daemon thread.
setDaemon() Sets the thread to be a daemon thread.
getContextClassLoader( Gets the context class loader of the thread.
)
setContextClassLoader( Sets the context class loader of the thread.
)
Example:
class T1 extends Thread
{
public void run(){
[Link]("Start With T1");
for(int i=0; i<9; i++){
[Link]("i= "+i+" ");
}
[Link]("Exit in T1");
}}
class T2 extends Thread
{
public void run(){
[Link]("Start With T2");
try{
for(int j=0; j<9; j++){
[Link](1000);
[Link]("j= "+j+" ");
}
[Link]("Exit in T2");
}
catch(Exception e){
[Link](e);
}
}}
class T3 extends Thread
{
public void run(){
[Link]("Start With T3");
for(int k=0; k<9; k++){
[Link]("k= "+k+" ");
}
[Link]("Exit in T3");
}}
class Threads{
public static void main(String args[]){ T1 obj1=new T1();
T2 obj2=new T2();
T3 obj3=new T3();
[Link](10);
/*[Link]([Link]()+1);*/
[Link]();
[Link]();
[Link]();
}}
Output:
Networking features
Networking:
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources. (or) Group of computers that are linked
together to share the information with other computers. The [Link] package
supports two protocols,
● TCP (Transmission Control Protocol)
● UDP (User Datagram Protocol)
Transmission Control Protocol:
● TCP is connection-oriented protocol (Wired) which means it requires
connection prior to the communication.
● TCP is a reliable communication.
● In TCP, the two ends of the communication link must be connected at all
times during the communication.
● TCP is a transport layer protocol.
● TCP protocol ensures that the data is received correctly, no data is missing
and in order.
● TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
● TCP is typically used for applications that require reliable communication,
such as file transfer and email.
User Datagram Protocol:
● UDP is a connectionless protocol (Wireless) which means it does not
require any connection.
● UDP is a faster communication.
● In UDP, no connection is established before data is sent.
● UDP is a transport layer protocol.
● It is also known as the "fire-and-forget" protocol as it sends the data and
does not care whether the data is received or not.
● UDP is typically used for applications that require fast communication,
such as streaming video and online gaming.
Advantage of Java Networking:
1. Sharing resources
2. Centralize software management
Java Networking Terminology:
● IP Address
● Protocol
● Port Number
● MAC Address
● Connection-oriented and connection-less protocol
● Socket
IP Address:
● An Internet Protocol (IP) address is a unique numerical identifier for every
device or network that connects to the internet.
● It is composed of octets that range from 0 to 255.
( [Link] to [Link])
● It is a logical address that can be changed.
● For example: [Link]
● The four sections of an IP address – network class, network, subnet, and
device.
Protocol:
In networking, a protocol is a set of rules for formatting and processing data.
Some of mostly used protocols are,
● SMTP (Simple Mail Transfer Protocol)
● PPP (Point-to-Point Protocol)
● FTP (File Transfer Protocol)
● SFTP (Secure File Transfer Protocol)
● HTTP (Hyper Text Transfer Protocol)
● POP (Post Office Protocol)
Port Number:
● The port number is used to uniquely identify different applications.
● It acts as a communication endpoint between applications.
● The port number is associated with the IP address for communication
between two applications.
● There are 65,535 port numbers, but not all are used every day.
MAC Address:
● MAC (Media Access Control) address is a unique identifier of NIC
(Network Interface Controller).
● A network node can have multiple NIC but each with unique MAC address.
● It contains a 48 bit or 64-bit address, which is combined with the network
adapter.
● MAC address can be in hexadecimal composition.
● In simple words, a MAC address is a unique number that is used to track a
device in a network.
Connection-oriented and connection-less protocol:
● In connection-oriented protocol, acknowledgement is sent by the receiver.
So it is reliable but slow.
● The example of connection-oriented protocol is TCP.
● But, in connection-less protocol, acknowledgement is not sent by the
receiver. So it is not reliable but fast.
● The example of connection-less protocol is UDP.
Socket:
● A socket is an endpoint between two way communications.
● The socket mechanism presents a method of inter-process communication
(IPC) by setting named contact points between which the communication
occurs.
● A socket is tied to a port number so that the TCP layer can recognize the
application to which the data is intended to be sent.
The 7 layers of the OSI model in Java:
● Physical Layer:
○ This layer is responsible for the physical transmission of data over a
network medium.
○ It is the lowest layer of the OSI model.
○ It establishes, maintains and deactivates the physical connection.
Main Functions of the Physical Layer
1. Bit Transmission
o Transfers data as electrical, optical, or radio signals
o Does not understand data meaning—only bits
2. Transmission Media
o Defines the medium used:
▪ Twisted pair cable
▪ Coaxial cable
▪ Optical fiber
▪ Wireless (radio waves)
3. Data Rate
o Specifies the speed of data transfer (bps, Mbps, Gbps)
4. Synchronization
o Ensures sender and receiver are synchronized at bit level
5. Physical Topology
o Defines how devices are connected
o Examples: Bus, Star, Ring, Mesh
6. Transmission Mode
o Simplex (one-way)
o Half-duplex (two-way, not simultaneous)
o Full-duplex (two-way, simultaneous)
● Data Link Layer:
○ This layer is responsible for the reliable transmission of data frames
between two directly connected devices.
○ It provides error detection and correction, as well as flow control.
Main Functions of Data Link Layer
1. Framing
o Divides the data into frames
o Adds header and trailer to each frame
2. Physical Addressing
o Uses MAC address (Media Access Control)
o Each device has a unique MAC address
3. Error Detection
o Detects errors using CRC (Cyclic Redundancy Check- to
detect errors in data transmission)
o Requests retransmission if error occurs
4. Flow Control
o Prevents a fast sender from overwhelming a slow receiver
o Techniques: Stop-and-Wait, Sliding Window
● Network Layer:
○ This layer is responsible for routing and forwarding data packets from
the source to the destination.
○ It provides logical addressing and path selection.
○ Main Functions of Network Layer
● Logical Addressing
○ Uses IP address (IPv4 / IPv6)
○ Identifies source and destination systems uniquely
● Routing
○ Determines the best path to send data
○ Uses routing algorithms and routing tables
● Packet Forwarding
○ Forwards packets from one router to another
○ Works between different networks
● Packetization
○ Breaks data into packets
○ Adds IP header information
● Congestion Control
○ Controls traffic to avoid network congestion
● Fragmentation and Reassembly
○ Breaks large packets into smaller fragments
○ Reassembles them at the destination
● Transport Layer:
○ This layer is responsible for providing reliable end-to-end
communication between applications.
○ The main responsibility of the transport layer is to transfer the data
completely.
○ It receives the data from the upper layer and converts them into
smaller units known as segments.
○ The two protocols used in this layer are: TCP ,UDP
Main Functions of Transport Layer
1. Process-to-Process Delivery
o Delivers data between applications on different hosts
o Uses port numbers
2. Segmentation and Reassembly
o Breaks data into segments
o Reassembles them at the destination
3. Connection Control
o Connection-oriented (TCP)
o Connectionless (UDP)
4. Error Control
o Error detection and recovery
o Uses acknowledgements and retransmissions
5. Multiplexing and Demultiplexing
o techniques used in computer networks to efficiently share
communication resources by allowing multiple signals or data
streams to use a single transmission medium.
● Session Layer:
○ This layer is responsible for establishing, managing, and terminating
sessions between applications.
Main Functions of Session Layer
1. Session Establishment
o Starts a communication session between two applications
2. Session Maintenance
o Keeps the session active during data transfer
3. Session Termination
o Properly closes the session after communication ends
4. Dialog Control
o Controls who can transmit data and when
o Supports:
▪ Half-duplex
▪ Full-duplex
5. Synchronization
o Inserts checkpoints in data transfer
o Allows recovery from failures without restarting entire transmission
● Presentation Layer:
○ This layer is responsible for transforming data into a format that can
be understood by the receiving application.
○ It acts as a data translator for a network.
○ The Presentation layer is also known as the syntax layer.
Main Functions of Presentation Layer
1. Data Translation
o Converts data formats between systems
o Example: ASCII ↔ Unicode, EBCDIC ↔ ASCII
2. Encryption
o Encrypts data before transmission
o Decrypts data at the receiver side
o Ensures data security
3. Compression
o Reduces data size for faster transmission
o Decompression at receiver side
4. Syntax and Semantics
o Defines how data is structured and interpreted
● Application Layer:
○ An application layer is not an application, but it performs the application
layer functions.
○ An application layer serves as a window for users.
○ This layer provides the network services to the end-users.
○ It handles issues such as network transparency, resource allocation, etc.
○ It includes protocols such as HTTP, FTP, and SMTP.
■ File transfer, access, and management (FTAM)
■ Mail services
■ Directory services
Media techniques
○ The Java Media Framework (JMF) is a Java library that provides a
comprehensive set of APIs for working with audio, video, and other time-
based media to be added to Java applications and applets.
○ JMF is a powerful tool for developing multimedia applications in Java.
1. Creating media player:
● Create the URL for media file.
● Create the player for the media.
● Tell the player to prefetch.
● Add the player to the applet.
● Start the player.
● init() method.
2. Prefetching the Media
● Prefetching causes two things:
* The player goes through a process called realization.
* It then starts to download the media file so that some of it can be
cached.
● This reduces the latency time before the player can start actually playing
the media.
● start() method.
3. Adding Player to your Application
● The player itself is not an AWT component. So you don't add the player
it self, but it's visual representation.
● To get the visual component, player has a method called
getVisualComponent().
● Player has a method called getState() that returns the state of the current
player.
● ControllerListener has one method- ControllerUpdate(ControllerEvent).
4. Cleaning Up and Stopping the Player
● stop() method must be used to stop the media player and clean up.
● The player has deallocate() method. As soon as you know that you no
longer need a media, you should tell the player to deallocate it so that it
can be garbage collected.
5. States of the Players
● Unrealized: At this stage, the player does not know anything about the
media except what the URL to the media is.
● Realizing: In the realizing state, the player acquired all of resources that
are non-exclusive.
● Realized: When the player enters the realized state, the
RealizeCompleteEvent is issued.
● Prefetching: To get the player to move into the prefetching state, you
can use the prefetch() method.
● Prefetched: Entering the prefetched state, a player issues the
PrefetchCompleteEvent.
● Started: When player is started, it enters the started state.
6. Adding Controls to the Players
● Each type of the player has the capability to give you a set of controls
using the ControlPanelComponent() method.
● Like the getVisualComponent() method, the
getControlPanelComponent() cannot be used until after the player has
been realized.
7. Setting the media time and Changing rate
● The setMediaTime() method takes long parameter and that number
represents the time in nanoseconds.
● The setRate() method returns to you the actual rate that has been applied.
8. Features and Formate of media
● JMF supports many popular media formats such as JPEG, MPEG
QuickTime, AVI, WAV, MP3, GSM and MIDI.
● JMF supports popular media access protocols such as file, HTTP,
HTTPS, FTP, RTP, and RTSP.