AOT Unit 1
AOT Unit 1
AOT Unit 1
Introduction to JavaScript
Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML form
and respond to user events such as mouse clicks, form input, and page navigation. Useful
libraries for the client side are AngularJS, ReactJS, VueJS, and so many others.
Server-side: It supplies objects relevant to running JavaScript on a server. For if the server-
side extensions allow an application to communicate with a database, and provide continuity
of information from one invocation to another of the application, or perform file manipulations
on a server. The useful framework which is the most famous these days is node.js.
Imperative language In this type of language we are mostly concerned about how it is to be
done. It simply controls the flow of computation. The procedural programming approach,
object, oriented approach comes under this as async await we are thinking about what is to be
done further after the async call.
Declarative programming In this type of language we are concerned about how it is to be
done, basically here logical computation requires. Her main goal is to describe the desired
result without direct dictation on how to get it as the arrow function does.
JavaScript can be added to your HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
External JS: We can write JavaScript code in another files having an extension.js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>
Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
</html>
History of JavaScript: It was created in 1995 by Brendan Eich while he was an engineer at
Netscape. It was originally going to be named LiveScript but was renamed. Unlike most
programming languages, JavaScript language has no concept of input or output. It is designed
to run as a scripting language in a host environment, and it is up to the host environment to
provide mechanisms for communicating with the outside world. The most common host
environment is the browser.
Features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.
Applications of JavaScript:
Web Development: Adding interactivity and behavior to static sites JavaScript was invented
to do this in 1995. By using AngularJS that can be achieved so easily.
Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps then
we only need to click and drag the mouse. All detailed view is just a click away, and this is
possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that
provide extra power to the code. The Electron and React are helpful in this department.
Server Applications: With the help of Node.js, JavaScript made its way from client to server
and Node.js is the most powerful on the server side.
Games: Not only in websites, but JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development as
well. It provides the EaseJS library which provides solutions for working with rich graphics.
Smartwatches: JavaScript is being used in all possible devices and applications. It provides a
library PebbleJS which is used in smartwatch applications. This framework works for
applications that require the Internet for their functioning.
Art: Artists and designers can create whatever they want using JavaScript to draw on HTML
5 canvas, and make the sound more effective also can be used p5.js library.
Machine Learning: This JavaScript ml5.js library can be used in web development by using
machine learning.
Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating mobile
applications. This is a Framework for building web and mobile apps using JavaScript. Using
React Native, we can build mobile applications for different operating systems. We do not
require to write code for different systems. Write once use it anywhere!
Limitations of JavaScript:
Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags
that load data such as <img>, <object>, <script>. These attacks are called cross-site script
ing the
details.
Performance: JavaScript does not provide the same level of performance as offered by many
traditional languages as a complex program written in JavaScript would be comparatively
slow. But as JavaScript is used to perform simple tasks in a browser, so performance is not
considered a big restriction in its use.
Complexity: To master a scripting language, programmers must have a thorough knowledge
of all the programming concepts, core language objects, and client and server-side objects
otherwise it would be difficult for them to write advanced scripts using JavaScript.
Weak error handling and type checking facilities: It is a weakly typed language as there is
no need to specify the data type of the variable. So wrong type checking is not performed by
compile.
excess strain on your CPU or RAM. JavaScript runs in the browser even though it has
complex paradigms and logic which means it uses fewer resources than other languages. For
example, NodeJs, a variation of JavaScript not only performs faster computations but also
uses fewer resources than its counterparts such as Dart or Java.
Additionally, when compared with other programming languages, it has fewer in-built
libraries or frameworks, contributing as another reason for it being lightweight. However, this
brings a drawback in that we need to incorporate external libraries and frameworks.
Javascript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
Output of the above example
102 Shyam Kumar 40000
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Output of the above example
101 Ravi 50000
Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
JavaScript objects are containers for named values, called properties and methods.
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.
The DHTML application was introduced by Microsoft with the release of the 4th version of IE
(Internet Explorer) in 1997.
Components of Dynamic HTML
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It defines
the structure of a web page with various defined basic elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling
the style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell
the browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all
elements in HTML.
Uses of DHTML
o It is used for designing the animated and interactive web pages that are developed in
real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.
Features of DHTML
o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
o It provides the facility for using the events, methods, and properties. And, also provides
the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.
o The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.
2. It is used for developing and creating 2. It is used for creating and designing the
web pages. animated and interactive web sites or pages.
3. This markup language creates static 3. This concept creates dynamic web pages.
web pages.
4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.
5. The files of HTML are stored with the 5. The files of DHTML are stored with the
.html or .htm extension in a system. .dhtm extension in a system.
6. A simple page which is created by a 6. A page which is created by a user using the
user without using the scripts or styles HTML, CSS, DOM, and JavaScript
called as an HTML page. technologies called a DHTML page.
7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts with users.
DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as dynamic.
We can easily type the JavaScript code within the <head> or <body> tag of a HTML page. If
we want to add the external source file of JavaScript, we can easily add using the <src>
attribute.
Following are the various examples, which describes how to use the JavaScript technology
with the DHTML:
Document.write() Method
Example 1: The following example simply uses the document.write() method of JavaScript
in the DHTML. In this example, we type the JavaScript code in the <body> tag.
1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>
Output:
JavaScript and HTML event
A JavaScript code can also be executed when some event occurs. Suppose, a user clicks an
HTML element on a webpage, and after clicking, the JavaScript function associated with that
HTML element is automatically invoked. And, then the statements in the function are
performed.
Example 1: The following example shows the current date and time with the JavaScript and
HTML event (Onclick). In this example, we type the JavaScript code in the <head> tag.
1. <html>
2. <head>
3. <title>
4. DHTML with JavaScript
5. </title>
6. <script type="text/javascript">
7. function dateandtime()
8. {
9. alert(Date());
10. }
11. </script>
12. </head>
13. <body bgcolor="orange">
14. <font size="4" color="blue">
15. <center> <p>
16. Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
17. # to check the today's date and time.
18. </p> </center>
19. </font>
20. </body>
21. </html>
Output:
What is xml
Xml (eXtensible Markup Language) is a mark up language.
XML is designed to store and transport data.
describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
Note: Self-describing data is the data that describes both its content and structure.
What is mark-up language
A mark up language is a modern system for highlight or underline a document.
Students often underline or highlight a passage to revise easily, same in the sense of modern
mark up language highlighting or underlining is replaced by tags.
Why xml
Platform Independent and Language Independent: The main benefit of xml is that you can
use it to take data from a program like Microsoft SQL, convert it into XML then share that
XML with other programs and platforms. You can communicate between two platforms
which are generally very difficult.
The main thing which makes XML truly powerful is its international acceptance. Many
corporation use XML interfaces for databases, programming, office application mobile
phones and more. It is due to its platform independent feature.
Features and Advantages of XML
XML is widely used in the era of web development. It is also used to simplify data storage
and data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML
If you need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way you can focus on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will not
require any changes to the HTML.
With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.
2) XML simplifies data sharing
In the real world, computer systems and databases contain data in incompatible formats.
XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.
This makes it much easier to create data that can be shared by different applications.
3) XML simplifies data transport
One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.
4) XML simplifies Platform change
Upgrading to new systems (hardware or software platforms), is always time consuming.
Large amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.
5) XML increases data availability
Different applications can access your data, not only in HTML pages, but also from XML
data sources.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people, or
people with other disabilities.
6) XML can be used to create new internet languages
A lot of new Internet languages are created with XML.
Here are some examples:
XHTML
WSDL for describing available web services
WAP and WML as markup languages for handheld devices
RSS languages for news feeds
RDF and OWL for describing resources and ontology
SMIL for describing multimedia for the web
XML Validation
XML file can be validated by 2 ways:
DTD
XSD
DTD (Document Type Definition) and XSD (XML Schema Definition) are used to define
XML structure.
XML DTD
What is DTD
DTD stands for Document Type Definition. It defines the legal building blocks of an XML
document. It is used to define document structure with a list of legal elements and attributes.
Purpose of DTD
Its main purpose is to define the structure of an XML document. It contains a list of legal
elements and define the structure with the help of them.
Checking Validation
Before proceeding with XML DTD, you must check the validation. An XML document is
called "well-formed" if it contains the correct syntax.
A well-formed and valid XML document is one which have been validated against DTD.
Let's take an example of well-formed and valid XML document. It follows all the rules of DTD.
employee.xml
1. <?xml version="1.0"?>
2. <!DOCTYPE employee SYSTEM "employee.dtd">
3. <employee>
4. <firstname>vimal</firstname>
5. <lastname>jaiswal</lastname>
6. <email>vimal@javatpoint.com</email>
7. </employee>
In the above example, the DOCTYPE declaration refers to an external DTD file. The content
of the file is shown in below paragraph.
employee.dtd
1. <!ELEMENT employee (firstname,lastname,email)>
2. <!ELEMENT firstname (#PCDATA)>
3. <!ELEMENT lastname (#PCDATA)>
4. <!ELEMENT email (#PCDATA)>
Description of DTD
<!DOCTYPE employee : It defines that the root element of the document is employee.
<!ELEMENT employee: It defines that the employee element contains 3 elements "firstname,
lastname and email".
<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-
able data type).
<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able
data type).
<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data
type).
A doctype declaration can also define special strings that can be used in the XML file.
1. An ampersand (&)
2. An entity name
3. A semicolon (;)
XML Schema
XML schema is a language which is used for expressing constraint about XML documents.
There are so many schema languages which are used now a days for example Relax- NG and
XSD (XML schema definition).
An XML schema is used to define the structure of an XML document. It is like DTD but
provides more control on XML structure.
Checking Validation
An XML document is called "well-formed" if it contains the correct syntax. A well-formed and
valid XML document is one which have been validated against Schema.
employee.xsd
1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
3. targetNamespace="http://www.javatpoint.com"
4. xmlns="http://www.javatpoint.com"
5. elementFormDefault="qualified">
6. <xs:element name="employee">
7. <xs:complexType>
8. <xs:sequence>
9. <xs:element name="firstname" type="xs:string"/>
10. <xs:element name="lastname" type="xs:string"/>
11. <xs:element name="email" type="xs:string"/>
12. </xs:sequence>
13. </xs:complexType>
14. </xs:element>
15.
16. </xs:schema>
Let's see the xml file using XML schema or XSD file.
employee.xml
1. <?xml version="1.0"?>
2. <employee
3. xmlns="http://www.javatpoint.com"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://www.javatpoint.com employee.xsd">
6. <firstname>vimal</firstname>
7. <lastname>jaiswal</lastname>
8. <email>vimal@javatpoint.com</email>
9. </employee>
1. simpleType
2. complexType
simpleType
The simpleType allows you to have text-based elements. It contains less attributes, child
elements, and cannot be left empty.
complexType
The complexType allows you to hold multiple attributes and elements. It can contain additional
sub elements and can be left empty.
1. window.document
Is same as
1. document
According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
Let's see the properties of document object that can be accessed and modified by the document
object.
Methods of document object
Method Description
writeln("string") writes the given string on the doucment with newline character at the end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>
The core Presenting XML mark-up language is currently being further developed in a
companion project, Serving XML. Anyone interested primarily in the command line
examples should use the Serving XML software instead.
Presenting XML is a Java web application framework for presenting HTML, PDF, WML
etc. in a device independent manner. It aims to achieve a complete separation of content and
presentation. It supports various kinds of content including XML files, dynamic content, SQL
result sets and flat files. It provides a declarative way for applying filters and XSLT
transforms to a stream of XML content in a pipeline. It allows user defined filters and
serializers written as Java plug-ins. It is component based and extendible.
Presenting XML may be used as a command line tool or as a framework for a servlet-based
web application. Simple examples with XML, XSLT, and Java are included in the
distribution. There are command line examples for converting flat files to XML (and vice
versa), for converting SQL results to XML, for applying a sequence of XSLT transforms and
SAX filters in a pipeline, and for setting up streaming filters.
There is a sample web application that illustrates how to build a simple shopping cart.
The last Presenting XML file distribution may be downloaded from SourceForge. It includes
Java source code and ant build files as well as binary jar files, a sample web application, and
run scripts. It includes api documentation and a user guide. It also includes a number of third
party jar files including Saxon (also Xalan), Apache Xerces, Sun's Multi-Schema XML
Validator, and the Apache fop pdf driver. It includes everything for running the sample web
application except the Java JDK and a web server.
Presenting XML requires Java JDK 1.3 or later (it will not work with earlier versions.) It
also requires a web server. The examples are configured to work with Jakarta Tomcat 4.0,
which may be downloaded and installed separately. The WML sample pages require a WAP
browser. A free WAP browser emulator may be obtained from OPENWAVE.
Java Applet
Note:
java.applet package package has been deprecated in Java 9 and later versions,as
applets are no longer widely used on the web.
-
company which developed Java) contracted with other company known as
It is important to understand the order in which the various methods shown in the above
image are called. When an applet begins, the following methods are called, in this
sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( )
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution
at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet when it goes to another page, for example. When stop( ) is called,
the applet is probably running. You should use stop( )
run when the applet is not visible. You can restart them when start( ) is called if the user
returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Creating Hello World applet :
Java
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
Explanation:
1. The above java program begins with two import statements. The first import
statement imports the Applet class from applet package. Every AWT-
based(Abstract Window Toolkit) applet that you create must be a subclass
(either directly or indirectly) of Applet class. The second statement import
the Graphics class from AWT package.
2. The next line in the program declares the class HelloWorld. This class must be
declared as public because it will be accessed by code that is outside the
program. Inside HelloWorld, paint( ) is declared. This method is defined by the
AWT and must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of
the Graphics class. This method outputs a string beginning at the specified X,Y
location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( )
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do
not begin execution at main( ) main( ) method.
Instead, an applet begins execution when the name of its class is passed to an applet viewer
or to a network browser.
Running the HelloWorld Applet :
After you enter the source code for HelloWorld.java, compile in the same way that you
have been compiling java programs(using javac command). However, running HelloWorld
with the java command will generate an error because it is not an application.
java HelloWorld
3. appletviewer with java source file : If you include a comment at the head of your Java
source code file that contains the APPLET tag then your code is documented with a
prototype of the necessary HTML statements, and you can run your compiled applet merely
by starting the applet viewer with your Java source code file. If you use this method, the
HelloWorld source file looks like this :
Java
>
With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
:
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 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()
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
windowActivated()
WindowListener windowDeactivated()
windowOpened()
Listener Interface Methods
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Output
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.
Event Handling by Other Class
Java
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
Output
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
Handling anonymously
AWT in java
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.
In this AWT tutorial, you will learn the basics of the AWT, including how to create
windows, buttons, labels, and text fields. We will also learn how to add event listeners to
components so that they can respond to user input.
By the end of this tutorial, you will have a good understanding of the AWT and be able to
create simple GUIs in Java.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface
(GUI) or Windows-based Java programs and Java AWT components are platform-
dependent, which means they are shown in accordance with the operating view.
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.
Points about Java AWT components
i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of components are platform
dependent.
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 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
Java AWT PopupMenu is a component that is used for dynamically popping up a menu that
appears when the user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible
2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by mouse events
generated by the user. Example: mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the
Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an
Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in
Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.
4. Java ItemListener
Java ItemListner is an interface which handles events related to item selection and
deselection those that occur with checkboxes, radio buttons, etc. There is only one Method
associated with ItemListner that is itemStateChanged(). This method provides information
about the event, i.e. source of the event and the changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)
5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state of key or can
be said for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window actions.
Events like opening , closing, minimizing, etc are handled using WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener
// Driver Class
public class AWT_Example {
// main function
public static void main(String[] args)
{
// Declaring a Frame and Label
Frame frame = new Frame("Basic Program");
Label label = new Label("Hello World!");
// Driver Class
public class Button_Example {
// main function
public static void main(String[] args)
{
// Creating instance of frame with the label
Frame frame = new Frame("Example 2");
// Creating instance of button with label
Button button = new Button("Click Here");