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

Advanced java unit1_notes

The document provides an overview of Java components and event handling, detailing various UI components like containers, buttons, labels, checkboxes, choices, and lists. It explains the concept of event handling in Java, including foreground and background events, the Delegation Event model, and how to register event listeners. Additionally, it covers the basics of threading in Java, including thread states, creation, and networking features such as TCP and UDP protocols.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Advanced java unit1_notes

The document provides an overview of Java components and event handling, detailing various UI components like containers, buttons, labels, checkboxes, choices, and lists. It explains the concept of event handling in Java, including foreground and background events, the Delegation Event model, and how to register event listeners. Additionally, it covers the basics of threading in Java, including thread states, creation, and networking features such as TCP and UDP protocols.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

COMPONENTS AND EVENT HANDLING:

A component is the fundamental user interface object in Java. Everything you see on the display in a
Java application is a component. This includes things like windows, panels, buttons, checkboxes,
scrollbars, lists, menus, and text fields. To be used, a component usually must be placed in a container.

So let us see each component in detail.

1. 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.
Panel: The Panel is also a Container that doesn’t include a title bar, menu, or border.
 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.

2. 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.
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
Example:

 Java

1 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
import java.awt.*;

// Driver Class
class SubmitButton extends Frame {
// main function
public static void main(String[] args)
{
// create instance of frame with label
Frame frame = new Frame("Submit form");

// create instance of button with label


Button button = new Button("Submit");

// set the position for the button in frame


button.setBounds(40, 130, 70, 20);

// adding button to the frame


frame.add(button);

// setting size for the frame


frame.setSize(500, 500);

// setting layout for the frame


frame.setLayout(null);

// visibility of frame to display the output\


// without this output will be blank
frame.setVisible(true);
}
}

We can run it by the following commands:

Output:

3. 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

2 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
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.
 LEFT: specifies that text should be aligned to left.
 RIGHT: specifies that text should be aligned to right.
 CENTER specifies that text should be aligned to the center.

4. Checkbox

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
Example 1:

 Java

// 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);

3 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
}
}

Output:

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:

6. List

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.
Example:

4 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
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 java.awt.event 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.

5 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
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 a button
ActionEvent ActionListener
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 component


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

6 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
Event Class Listener Interface Description

An event that occurs due to a sequence of


KeyEvent KeyListener
keypresses on the keyboard.

MouseListener & The events that occur due to the user interaction
MouseEvent
MouseMotionListener with the mouse (Pointing Device).

An event that specifies that the mouse wheel


MouseWheelEvent MouseWheelListener
was rotated in a component.

An event that occurs when an object’s text


TextEvent TextListener
changes.

An event which indicates whether a window has


WindowEvent WindowListener
changed its status or not.

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
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors
due to the unavailability of some packages.

Event Handling Within Class

 Java

// Java program to demonstrate the

7 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
// 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();
}
}

Output

After Clicking, the text field value is set to GFG!

8 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
Explanation
1. Firstly extend the class with the applet and implement the respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e. ActionEvent by addActionListener().
4. In the end, implement the abstract method.

Thread Concept in Java

A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a
program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept in Java. All the
tasks are executed without affecting the main program. In a program or process, all the threads have
their own separate path for execution, so each thread of a process is independent.

When multiple threads are executed in parallel at the same time, this process is known
as Multithreading.
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.

Thread Model

Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run)


A thread is in New when it gets CPU time.
9 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING
STI- NOTES 2K23
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution immediately.

Creating Thread

A thread is created either by "creating or implementing" the Runnable Interface or by extending


the Thread class. These are the only two ways through which we can create a thread.
Let's dive into details of both these way of creating a thread:

Thread Class

A Thread class has several methods and constructors which allow us to perform various operations on
a thread. The Thread class extends the Object class. The Object class implements
the Runnable interface. The thread class has the following constructors that are used to perform
various operations.

o Thread()

o Thread(Runnable, String name)

o Thread(Runnable target)

o Thread(ThreadGroup group, Runnable target, String name)

o Thread(ThreadGroup group, Runnable target)

o Thread(ThreadGroup group, String name)

o Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose instances are intended to be
executed by a thread. The runnable interface gives us the run() method to perform an action for the
thread.

start() method

The method is used for starting a thread that we have newly created. It starts a new thread with a new
callstack. After executing the start() method, the thread changes the state from New to Runnable. It
executes the run() method when the thread gets the correct time to execute it.
Let's take an example to understand how we can create a Java thread by extending the Thread class:
ThreadExample1.java

1. // Implementing runnable interface by extending Thread class


2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.

4. public void run()

10 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
5. {

6. int a= 10;

7. int b=12;

8. int result = a+b;

9. System.out.println("Thread started running..");

10. System.out.println("Sum of two numbers is: "+ result);

11. }

12. public static void main( String args[] )

13. {

14. // Creating instance of the class extend Thread class

15. ThreadExample1 t1 = new ThreadExample1();

16. //calling start method to execute the run() method of the Thread class

17. t1.start();

18. }

19. }

Networking features
Java Networking is a concept of connecting two or more computing devices together so that we can
share resources.
Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking

1. Sharing resources
2. Centralize software management
The java.net package supports two protocols,

1. TCP: Transmission Control Protocol provides reliable communication between the sender
and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.

2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet
of data to be transferred along two or more nodes

Java Networking Terminology

The widely used Java networking terminologies are given below:

1. IP Address
2. Protocol

11 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of


octets that range from 0 to 255.
It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

o TCP

o FTP

o Telnet

o SMTP

o POP etc.

3) 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.

4) 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.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) 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.

6) Socket

A socket is an endpoint between two way communications.

java.net package

The java.net package can be divided into two sections:

12 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers,
Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network
interfaces.

2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier,
URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource
pointed by URLs.
The java.net package provides many classes to deal with networking applications in Java. A list of
these classes is given below:

o Authenticator

o CacheRequest

o CacheResponse

o ContentHandler

o CookieHandler

o CookieManager

o DatagramPacket

o DatagramSocket

o DatagramSocketImpl

List of interfaces available in java.net package:

o ContentHandlerFactory

o CookiePolicy

o CookieStore

o DatagramSocketImplFactory
Media techniques:

Modern world's rich internet applications must be capable to play and edit the media files when
required. JavaFX provides the media-rich API that can play audio and video on the user's demand.
JavaFX Media API enables the users to incorporate audio and video into the rich internet applications
(RIAs). JavaFX media API can distribute the media content across the different range of devices like
TV, Mobile, Tablets and many more.
the capability of JavaFX to deal with the media files in an interactive way. For this purpose, JavaFX
provides the package javafx.scene.media that contains all the necessary
classes. javafx.scene.media contains the following classes.

1. javafx.scene.media.Media
2. javafx.scene.media.MediaPlayer
3. javafx.scene.media.MediaStatus
4. javafx.scene.media.MediaView

Media Events

13 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
The JavaFX team have designed media API to be event driven. The callback behaviour attached with
the media functions are used to handle media events. Instead of typing code for a button via a
EventHandler, a code is implemented that responds to the triggering of the media player's OnXXXX
events where XXXX is the event name.
java.lang.Runnable functional interfaces are used as the callbacks which are invoked when an event is
encountered. When playing the media content in javafx, we would create the Lambda expressions
(java.lang.Runnable interfaces) to be set on the onReady event. Consider the following example.

1. Media media = new Media(url);


2. MediaPlayer mediaPlayer = new MediaPlayer(media);
3. Runnable playMusic = () -> mediaPlayer.play();
4. mediaPlayer.setOnReady(playMusic);
The playMusic variable is assigned to a lambda expression. This get passed into the Media player's
setOnReady() method. The Lambda expression will get invoked when the onReady event is
encountered.

Possible media and media-player events are discussed in the following table.

Class Set On Method Description

Media setOnError() This method is invoked when an error occurs. It is the part of the class
Media.

MediaPlayer setOnEndOfMedia() The method is invoked when end of the media play is reached.

MediaPlayer setOnError() This method is invoked when an error occurs.

MediaPlayer setOnHalted() This method is invoked when the status of media changes to halted.

MediaPlayer setOnMarker() This method is invoked when the Marker event is triggered.

MediaPlayer setOnPaused() This method is invoked when a pause event occurs.

MediaPlayer setOnPlaying() This method is invoked when the play event occurs.

14 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
MediaPlayer setOnReady() This method is invoked when the media is in ready state.

MediaPlayer setOnRepeat() This method is invoked when the repeat property is set.

MediaPlayer setOnStalled() This method is invoked when the media player is stalled.

MediaPlayer setOnStopped() This method is invoked when the media player has stopped.

MediaView setOnError() This method is invoked when an error occurs in the media view.

We must notice that MediaPlayer class contains the most number of events triggered while MediaView
and Media classes contains one event each.

javafx.scene.media.Media class

The properties of the class are described in the following table. All the properties are the read only
except onError.

Property Description

duration The duration of the source media in seconds. This property is of object type of the class
Duration.

error This is a property set to media exception value when an error occurs. This property is of the
type object of the class MediaException.

height The height of the source media in pixels. This is an integer type property.

onError The event handler which is called when the error occurs. The method setOnError() is used to
set this property.

width The width of the source media in pixels. This is an integer type property

JavaFX.scene.media.MediaPlayer class

The properties of the class along with the setter methods are described in the following table.

Property Property Setter Methods

autoPlay This is the boolean type property. The true setAutoPlay(Boolean value)
value indicates the playing will be started as
soon as possible.

15 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23
currentTime This is an object type property of the class Can not be set as it is read only
Duration. It indicates the current media property.
playback time.

mute It is a boolean type property. It indicates SetMute(boolean value)


whether the audio is muted or not.

onEndOfMedia It is an object type property of the interface setOnEndOfMedia(java.lang.Runnable


Runnable. It is set to an Event Handler which value)
will be invoked when the end of the media file
is reached.

onPaused It is an object type property of the interface setOnPaused(java.lang.Runnable value)


Runnable. It indicates the EventHandler which
will be invoked when the status changed to
paused.

onPlaying It is an object type property of the interface setOnPlaying(java.lang.Runnable


Runnable. It indicates the EventHandler which value)
will be invoked when the status changed to
playing.

onReady It is an object type property of the interface setOnReady(java.lang.Runnable value)


Runnable. It indicates the EventHandler which
will be invoked when the status changed to
Ready.

onRepeat It is an object type property of the class setOnRepeat(java.lang.Runnable value)


MediaMarkerEvent. It indicates the
EventHandler which will be invoked when the
current time reaches the stop time and will be
repeating.

volume It is a double type property. It indicates the setVolume(double value)


volume at which the media should be playing.

16 DEPARTMENT OF BCA ADVANCED JAVA PROGRAMMING


STI- NOTES 2K23

You might also like